How to check whether Database Connection is Open

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"; 


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



About author

User avatar

Waqas Anwar

Founder of, Senior Consultant, Microsoft .NET and Web Technologies