Check if SQL Connection is Open or Closed

前端 未结 9 1717
春和景丽
春和景丽 2020-12-08 01:47

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

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

however, even the State is \'Op

相关标签:
9条回答
  • 2020-12-08 02:34

    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
        }
    
    0 讨论(0)
  • 2020-12-08 02:40

    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();
    }
    
    0 讨论(0)
  • 2020-12-08 02:47

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

    if(con.State == ConnectionState.Open){}
    
    0 讨论(0)
提交回复
热议问题