Check if SQL Connection is Open or Closed

前端 未结 9 1716
春和景丽
春和景丽 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:22

    Check if a MySQL connection is open

    ConnectionState state = connection.State;
    if (state == ConnectionState.Open)
    {
        return true;
    }
    else
    {
        connection.Open();
        return true;
    }
    
    0 讨论(0)
  • 2020-12-08 02:23

    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.

    0 讨论(0)
  • 2020-12-08 02:27

    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

    0 讨论(0)
  • 2020-12-08 02:29

    I use the following manner sqlconnection.state

    if(conexion.state != connectionState.open())
       conexion.open();
    
    0 讨论(0)
  • 2020-12-08 02:30

    you can also use this

    if (SQLCON.State == ConnectionState.Closed)
    {
         SQLCON.Open();
    }
    
    0 讨论(0)
  • You should be using SqlConnection.State

    e.g,

    using System.Data;
    
    if (myConnection != null && myConnection.State == ConnectionState.Closed)
    {
       // do something
       // ...
    }
    
    0 讨论(0)
提交回复
热议问题