【发布时间】:2016-01-15 19:40:40
【问题描述】:
我想测试是否存在带有 tcp 套接字的 SQL Server(如果服务器不存在则更快)。
如果连接字符串是这样的:
name="DefaultConnection"
connectionString="Data Source=COMPUTERNAME\SQLSERVERNAME;Initial Catalog=TestDb;Integrated Security=False;User ID=sa;Password=1234;MultipleActiveResultSets=True"/>
我想用这个方法:
public bool CheckServerAvailablity(string sServerAddressOrName)
{
try
{
string connectString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
// Retrieve the DataSource property.
string sServerAddressOrName = builder.DataSource;
int port = 1433;
IPHostEntry ipHostEntry = Dns.GetHostEntry(sServerAddressOrName);
IPAddress ipAddress = ipHostEntry.AddressList[0];
TcpClient TcpClient = new TcpClient();
TcpClient.Connect(ipAddress, port);
TcpClient.Close();
return true;
}
catch
{
return false;
}
}
问题是:sServerAddressOrName = COMPUTERNAME\SQLSERVERNAME,但我只需要COMPUTERNAME。
那么,问题是如何只获得COMPUTERNAME?
提前致谢!
【问题讨论】:
-
您假设 SQL Server 正在侦听 1433 端口。但是 1433 是默认实例的默认端口。命名实例默认使用动态端口。此外,可以将默认实例配置为侦听另一个端口。因此,即使对于默认实例,CheckServerAvailablity 也不起作用。从连接字符串中获取计算机名称是一个小问题,您可以使用 String.Split() 来解决它。但是获取 SQL Server 监听的端口不是,您需要与 SQL Server Browser 服务通信
-
感谢您的评论。你说的很对,但是这个问题所属的环境,只能使用 TCP/IP 连接。
标签: c# sql-server connection-string