Check if SQL program server is available?

I am looking for a way to test the availability of SQL Server as this is a MySQL solution if there is no better method.

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

+3
source share
3 answers

I would create a new connection string with a very short connection 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
+1
source

Here's a software 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
}
+1
source

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
       }
   }
+1
source

Source: https://habr.com/ru/post/1713949/


All Articles