Check if SQL connection is open or closed

How do you check if it is open or closed? I used

if (SQLOperator.SQLCONNECTION.State.Equals("Open")) 

however, even the state is “open”, it is not executed during this check.

+71
c # sqlconnection
Aug 04 2018-11-11T00:
source share
8 answers

You must use SqlConnection.State

eg,

 if (myConnection != null && myConnection.State == ConnectionState.Closed) { // do something // ... } 
+116
Aug 04 '11 at 3:15 a.m.
source share
— -

Here is what I use:

 if (mySQLConnection.State != ConnectionState.Open) { mySQLConnection.Close(); mySQLConnection.Open(); } 

The reason I am not just using:

 if (mySQLConnection.State == ConnectionState.Closed) { mySQLConnection.Open(); } 

This is because ConnectionState could also be:

 Broken, Connnecting, Executing, Fetching 

In addition to

 Open, Closed 

In addition, Microsoft states that Closing and then Reopening the connection will “update the status value”. See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v = vs .110). Aspx

+42
Mar 28 '14 at 19:10
source share

.NET documentation says: Status property: Bitwise combination of ConnectionState values

So, I think you should check

 !myConnection.State.HasFlag(ConnectionState.Open) 

instead

 myConnection.State != ConnectionState.Open 

since a state can have multiple flags.

+13
Dec 18 '15 at 14:19
source share

Check if MySQL connection is open

 ConnectionState state = connection.State; if (state == ConnectionState.Open) { return true; } else { connection.Open(); return true; } 
+9
Nov 13 '12 at 20:35
source share

you can also use this

 if (SQLCON.State == ConnectionState.Closed) { SQLCON.Open(); } 
+5
Nov 02 '12 at 7:25
source share

This code is a bit more secure before you open the connection, check the status. If the state of the connection is Broken, we should try to close it. Broken means that the connection was previously open and does not work correctly. The second condition determines that the connection state must be closed before trying to open it again so that the code can be called again.

 // Defensive database opening logic. if (_databaseConnection.State == ConnectionState.Broken) { _databaseConnection.Close(); } if (_databaseConnection.State == ConnectionState.Closed) { _databaseConnection.Open(); } 
+4
Jun 08 '17 at 17:50
source share

To check the status of the database connection, you can simply do the following

 if(con.State == ConnectionState.Open){} 
+3
Aug 27 '15 at 5:19
source share

I am using the following sqlconnection.state method

 if(conexion.state != connectionState.open()) conexion.open(); 
-3
May 19 '12 at
source share



All Articles