我只想检查我是否与SQL Server有连接,以便将本地数据库同步到该服务器。而且,如果我不必跳过它。
此外,它也应可用于wifi和电缆连接。
当它与wifi连接时,我的网络关闭了,但是方法
System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
返回true,所以该方法对我来说不太好。
我也尝试这样检查与我的SQL Server的连接
public bool TestServerConnection()
{
using (SqlConnection openCon = new SqlConnection(connectionString))
{
try
{
string saveStaff = "select 1";
SqlCommand command = new SqlCommand(saveStaff, openCon);
command.CommandTimeout = 1;
openCon.Open();
if (openCon.State == ConnectionState.Open)
{
return true;
}
else
{
return false;
}
}
catch (Exception)
{
return false;
}
}
}
使用此连接字符串
Data Source=CV-TED-SQL1;Initial Catalog = PulserDb; Integrated Security=true;MultipleActiveResultSets=True;
但是例如当我没有连接时,例如当我将Data Source=CV-TED-SQL1;
更改为Data Source=CV-TED-SQL11;
时,openCon.Open();
大约需要10秒钟。
太久了..
有什么最快的方法吗?
我无法更改我的连接字符串,也许我只能为我的方法更改它,并在此方法结束时将其更改回
感谢您的帮助。
如果无法更改连接字符串以添加连接超时密钥,则可以使用SqlConnectionStringBuilder如下所示在运行时轻松更改连接字符串,如下所示:
SqlConnectionStringBuilder scb = new SqlConnectionStringBuilder(connectionString);
scb.ConnectTimeout = 5; // 5 seconds wait 0 = Infinite (better avoid)
connectionString = scb.ToString();
Console.WriteLine(connectionString);
using(SqlConnection cnn = new SqlConnection(connectionString)
{
}