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.
Tweet
5 comments:
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.
One use I see is to make this a service that continously checks if the connection exists and pauses tasks if the connection breaks.
where are old post button. are you hungry eating them.
5 year later , but very good job !! Thanks for this very utility func !
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.
Post a Comment