Check Database connection using C# or VB.NET

As a programmer, one of the most common tasks in your application is to connect to the database. Here’s a very simple way to check your database connection before you start any task or use this as a service to check the connection and pause tasks if the connection breaks.

C#

private static bool DBConnectionStatus()
{
try
{
using (SqlConnection sqlConn =
new SqlConnection("YourConnectionString"))
{
sqlConn.Open();
return (sqlConn.State == ConnectionState.Open);
}
}
catch (SqlException)
{
return false;
}
catch (Exception)
{
return false;
}
}

VB.NET (Converted Code)

Private Function DBConnectionStatus() As Boolean
Try
Using
sqlConn As New SqlConnection("YourConnectionString")
sqlConn.Open()
Return (sqlConn.State = ConnectionState.Open)
End Using
Catch
e1 As SqlException
Return False
Catch
e2 As Exception
Return False
End Try
End Function

The code above opens a connection to the database and returns a boolean depending on the database status.

5 comments:

  1. I really don't get why would I do that... It only means that at this point you have connectivity which is no guarantee that you;ll have that after you start using the connection.

    ReplyDelete
  2. One use I see is to make this a service that continously checks if the connection exists and pauses tasks if the connection breaks.

    ReplyDelete
  3. where are old post button. are you hungry eating them.

    ReplyDelete
  4. 5 year later , but very good job !! Thanks for this very utility func !

    ReplyDelete
  5. Hi brother ...above written code will still take at least 5 second to return false if it is not connected. Do you have a really faster way to check, any help would be greatly appreciated.


    Thanks in advance.

    ReplyDelete