[c#] Check if SQL Connection is Open or Closed

How do you check if it is open or closed I was using

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

however, even the State is 'Open' it fails on this check.

This question is related to c# ado.net sqlconnection

The answer is


I use the following manner sqlconnection.state

if(conexion.state != connectionState.open())
   conexion.open();

Check if a MySQL connection is open

ConnectionState state = connection.State;
if (state == ConnectionState.Open)
{
    return true;
}
else
{
    connection.Open();
    return true;
}

To check the database connection state you can just simple do the following

if(con.State == ConnectionState.Open){}

To check OleDbConnection State use this:

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

State return the ConnectionState

public override ConnectionState State { get; }

Here are the other ConnectionState enum

public enum ConnectionState
    {
        //
        // Summary:
        //     The connection is closed.
        Closed = 0,
        //
        // Summary:
        //     The connection is open.
        Open = 1,
        //
        // Summary:
        //     The connection object is connecting to the data source. (This value is reserved
        //     for future versions of the product.)
        Connecting = 2,
        //
        // Summary:
        //     The connection object is executing a command. (This value is reserved for future
        //     versions of the product.)
        Executing = 4,
        //
        // Summary:
        //     The connection object is retrieving data. (This value is reserved for future
        //     versions of the product.)
        Fetching = 8,
        //
        // Summary:
        //     The connection to the data source is broken. This can occur only after the connection
        //     has been opened. A connection in this state may be closed and then re-opened.
        //     (This value is reserved for future versions of the product.)
        Broken = 16
    }

Here is what I'm using:

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

The reason I'm not simply using:

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

Is because the ConnectionState can also be:

Broken, Connnecting, Executing, Fetching

In addition to

Open, Closed

Additionally Microsoft states that Closing, and then Re-opening the connection "will refresh the value of State." See here http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.state(v=vs.110).aspx


The .NET documentation says: State Property: A bitwise combination of the ConnectionState values

So I think you should check

!myConnection.State.HasFlag(ConnectionState.Open)

instead of

myConnection.State != ConnectionState.Open

because State can have multiple flags.


This code is a little more defensive, before opening a connection, check state. If connection state is Broken then we should try to close it. Broken means that the connection was previously opened and not functioning correctly. The second condition determines that connection state must be closed before attempting to open it again so the code can be called repeatedly.

// Defensive database opening logic.

if (_databaseConnection.State == ConnectionState.Broken) {
    _databaseConnection.Close();
}

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

you can also use this

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

You should be using SqlConnection.State

e.g,

using System.Data;

if (myConnection != null && myConnection.State == ConnectionState.Closed)
{
   // do something
   // ...
}

Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to ado.net

Error: No Entity Framework provider found for the ADO.NET provider with invariant name 'System.Data.SqlClient' How to fill a datatable with List<T> Populate data table from data reader Increasing the Command Timeout for SQL command how to resolve DTS_E_OLEDBERROR. in ssis Convert DataSet to List How to connect access database in c# MySQL Data Source not appearing in Visual Studio How do I get values from a SQL database into textboxes using C#? Connection to SQL Server Works Sometimes

Examples related to sqlconnection

How to write connection string in web.config file and read from it? How to run multiple SQL commands in a single SQL connection? SQL Server returns error "Login failed for user 'NT AUTHORITY\ANONYMOUS LOGON'." in Windows application Changing SqlConnection timeout How to use the ConfigurationManager.AppSettings Check if SQL Connection is Open or Closed in a "using" block is a SqlConnection closed on return or exception?