I have come up with the following method to determine is a database is up and running. This trys to open a database connection and if it fails it return false.
private static bool IsDatabaseConnectionUp(string connectionString)
{
System.Data.SqlClient.SqlConnection conn = null;
try
{
conn = new SqlConnection(connectionString);
conn.Open();
return conn.State == System.Data.ConnectionState.Open;
}
catch (SqlException)
{
// There was an error in opening the database so it is must not up.
return false;
}
finally
{
if (conn != null)
{
if (conn.State == System.Data.ConnectionState.Open)
{
conn.Close();
}
conn.Dispose();
}
}
}
Is this the best way to determine if this database is up? The reason I do not like this method it will rely on the timeout value, and will take as long as the timeout is set.
Is there a better way?
This really depends on exactly what you are trying to determine. If you are truly looking to determine if "The server is running, and able to be accessed", then I would say that this is most likely the most effective manner. The reason I say this is that the server itself could be up, but it might not be accepting connections, OR the connection that the application is using might be invalid (Incorrect username/password).
Therefore, given this, the timeout is a needed thing, as you want to validate true connection. If you want to simply see if the server is there, you could try pinging, but that simply tells you if the device is active, not necessarily if SQL Server is fully up and running, and available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With