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.
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.
just try to open a connection to it. if it fails it's not available. it's your best option.
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
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
}
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
}
}