我有这个简单的代码来测试数据库是否准备就绪:
Function testlocalcon() As Boolean
Dim constr As String = _clconstr
Try
Using t As New SqlConnection()
constr = constr & " ; Connect Timeout=1"
If Not t.State = Data.ConnectionState.Open Then
t.ConnectionString = constr
t.Open()
If t.State = Data.ConnectionState.Open Then
Return True
Else
Return False
End If
Else
Return True
End If
End Using
Catch ex As Exception
Return False
End Try
End Function
我不想执行查询,只是为了检查连接,但无论什么超时参数被忽略。我在这里搜索(Stackoverflow)和互联网,并没有发现如何解决这个问题。
还有其他人有这个问题吗?或者,对于如何让应用程序知道数据库已准备好,还有其他想法吗?
答案 0 :(得分:0)
我为不同的代码道歉,但这是C#,我过去曾经使用过它。它很简单,应该是可读的。
private SQLServerConnection
private SqlConnection _SQLServerConnection;
public SqlConnection SQLServerConnection
{
get
{
return _SQLServerConnection;
}
set
{
_SQLServerConnection = value;
}
}
private void SetSQLServerConnectionString (string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
SQLServerConnection = new SqlConnection("Password=" + saPassword + ";Persist Security Info=True;User ID=sa;Initial Catalog=" + databaseName + ";Data Source=" + sqlServerName + ";connection timeout=" + connectTimeout.ToString(CultureInfo.InvariantCulture));
}
internal bool TestSQLServerConnection(string sqlServerName, string databaseName, string saPassword, int connectTimeout)
{
try
{
SetSQLServerConnectionString(sqlServerName, databaseName, saPassword, connectTimeout);
SQLServerConnection.Open();
return true;
}
catch (SqlException e)
{
return false;
}
finally
{
SQLServerConnection.Close();
}
}