2009-07-30 68 views
3

我正在尋找一種方法來檢查SQL Server的可用性,例如MySQL solution,除非有更好的方法。檢查一個SQL服務器是否可用編程方式?

我的計劃是檢查SQL Server實例是否啓動/關閉,如果它已關閉,則通過try/catch向用戶顯示一條消息。

+0

是sql server本地還是遠程(或兩者)? – djangofan 2009-07-30 14:14:30

+0

遠程,即它位於不同的服務器上,但位於同一個域內 – 2009-07-30 14:27:05

回答

1

我將創建一個新的連接字符串用一個非常小的連接超時

Dim Conn As New SqlClient.SqlConnection("server=127.0.0.1;uid=username;pwd=password;database=mydatabasename;Connect Timeout=5") 

     Try 
      Conn.Open() 
     Catch exSQL As SqlClient.SqlException 
     If exSQL.Message.ToUpper().Contains("LOGIN FAILED") Then 
      MsgBox("Invalid User/Password") 
     Else 
      MsgBox("SQL Error: " & exSQL.Message) 
     End If 
     Exit Sub 
     Catch ex As Exception 
      MsgBox("Something went wrong.") 
      Exit Sub 
     Finally 
      Conn.Close() 
      Conn.Dispose() 
     End Try 
1

下面是使用SMO(Server管理對象)一個綱領性的解決方案...

Microsoft.SqlServer.Management.Smo.Server server = new Microsoft.SqlServer.Management.Smo.Server(); 
try 
{ 
    // You can modify your connection string here if necessary 
    server.ConnectionContext.ConnectionString = "Server=servername; User ID=username; Password=password"; 
    server.ConnectionContext.Connect(); 
} 
catch (Exception ex) 
{ 
    // Handle your exception here 
} 
if (server.ConnectionContext.IsOpen) 
{ 
    // Show message that the server is up 
} 
else 
{ 
    // Show message that the server is down 
} 
1

我想補充一個異常到你的try/catch /最後查找sql​​連接狀態。我忘記了物體和財產,但我相信你可以找到它。典型的SQL查詢方式(我習慣了):

using (SqlConnection) { 
     try { 
      // open connection, try to execute query and fetch results 


     } catch (Connection.IsOpen) { 
     // add the catch exception for connection status here 


     } finally { 
      //close connection 
     } 
    } 
相關問題