2010-06-10 52 views
1

我有這個簡單的代碼來測試一個DB已準備就緒:超時在SQL連接不工作

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 

我不想執行查詢時,只檢查連接,但無論什麼時候out參數被忽略。我在這裏搜索(Stackoverflow)和互聯網,並沒有發現如何解決這個問題。

其他任何人都有這個問題?或者,有沒有關於如何讓應用程序知道數據庫已準備好的其他想法?

+0

您試圖設置連接超時或命令超時嗎?他們是兩件不同的事情。 – Barry 2010-06-10 17:39:51

回答

0

我爲代碼差異appologize,但這是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(); 
    } 
} 
+1

嘿約翰謝謝,但你的代碼是完全一樣的,它不工作,它只是忽略超時值... 我也複製你的代碼並使用它,但超時參數被忽略.. 任何其他thougts? – carlos 2010-06-10 03:43:57

+0

我不同意我一直在使用此代碼安裝程序來驗證服務器是否存在,並且它工作得很好。 – 2010-06-10 03:51:35

+0

只是要問......如果您只是檢查服務器是否可用,爲什麼還要擔心超時? – 2010-06-10 03:53:32