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.






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

5 comments:

Anonymous said...

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.

Suprotim Agarwal said...

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

Anonymous said...

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

Unknown said...

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

Rohan said...

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.