Bryan Denny
Bryan Denny

Reputation: 27596

Check if a SQL server is available programmatically?

I'm looking for a way to check SQL Server availability like this MySQL solution, unless there is a better method.

My plan is to check if the SQL Server instance is up/down, and if it is down then display a message to the user, all via a try/catch.

Upvotes: 3

Views: 5636

Answers (3)

Mike Z
Mike Z

Reputation: 96

I would create a new connection string with a very small connect timeout

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

Upvotes: 1

Donut
Donut

Reputation: 112895

Here's a programmatic solution using SMO (Server Management Objects)...

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
}

Upvotes: 1

osij2is
osij2is

Reputation: 1556

I would add an exception to the top of your try/catch/finally to look for the sql connection status. I forget the object and property, but I'm sure you can find that out. The typical SQL way of querying (that I'm used to):

    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
       }
   }

Upvotes: 1

Related Questions