2009-07-30 44 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 
     } 
    } 
相关问题