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.



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

4 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.

Aristoteles deaMundo said...

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