检查SQL Server是否以编程方式可用?

时间:2009-07-30 13:14:40

标签: sql-server-2005

我正在寻找一种检查SQL Server可用性的方法,如MySQL solution,除非有更好的方法。

我的计划是检查SQL Server实例是否已启动/关闭,如果它已关闭,则向用户显示一条消息,全部通过try / catch。

3 个答案:

答案 0 :(得分: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 :(得分:1)

这是使用SMO(服务器管理对象)的程序化解决方案......

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
}

答案 2 :(得分:1)

我会在try / catch / finally的顶部添加一个异常来查找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
       }
   }