"If at first you don't succeed; call it version 1.0" :-Unknown

Pages

Friday, November 19, 2010

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.


Have a nice day... 'N happy Coding :)

No comments: