How to check whether Database Connection is Open

Waqas Anwar
29 June 2009
8600 Views

You have a database connection and you want to check the current state of connection whether it is open or not, you can use State property available in connection class and compare it with one of the value available in System.Data.ConnectionState enumeration

SqlConnection con = new SqlConnection();

con.ConnectionString = "Server=TestServer;Database=TestDatabase;uid=test;pwd=test";

con.Open();

if (con.State == System.Data.ConnectionState.Open)
{
   Console.WriteLine("Database Connection is Open");
}