ExecuteNonQuery requires an open and available Connection. The connection's current state is closed

后端 未结 5 1112
情书的邮戳
情书的邮戳 2021-02-07 11:55

ExecuteNonQuery requires an open and available Connection. The connection\'s current state is closed.

What am I doing wrong here? I\'m assuming you can

相关标签:
5条回答
  • 2021-02-07 12:02

    Right here, your SqlDataReader will close the connection when it completes:

    // Set all to 0 
    using (SqlCommand cmd = new SqlCommand("SELECT ID FROM tblSiteSettings WHERE ID = " + revertingID, cn)) 
    { 
        // If it exists 
        SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection); 
        if (rdr.Read()) 
        { 
            rowsReturned = true; 
        } 
        rdr.Close(); 
    } 
    

    Later, the "Set new active and reset others" section will fail, because the connection is closed.

    0 讨论(0)
  • 2021-02-07 12:17

    Just add cn.Open before, or do not close it.

    0 讨论(0)
  • 2021-02-07 12:20

    It appears you are doing a read before doing your ExecuteNonQuery. In your first call to SqlCommand (for the SELECT), you are closing the connection after the read is complete.

    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    

    Remove the command behavior, you should be good to go, or re-open the connection in your next if statement.

    This

    SqlDataReader rdr = cmd.ExecuteReader();
    

    Or this

    if (rowsReturned == true){
       cn.open();
    
    0 讨论(0)
  • 2021-02-07 12:21

    Your problem is:

    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
    

    You should just call cmd.ExecuteReader()' if you want to use the connection again prior to "getting rid" of it. If you want to get an understanding for what the CommandBehaviour.CloseConnection part does/means then the documentation for SqlCommand.ExecuteReader is a good bet. There's also documentation to tell you what all the possible values of the CommandBehaviour enumeration are. Essentially CommandBehaviour.CloseConnection does the following:

    When the command is executed, the associated Connection object is closed when the associated DataReader object is closed.

    If you have no special need to specify a CommandBehaviour, then either specify CommandBehaviour.Default, or don't specify one at all. CommandBehaviour.Default is:

    The query may return multiple result sets. Execution of the query may affect the database state. Default sets no CommandBehavior flags, so calling ExecuteReader(CommandBehavior.Default) is functionally equivalent to calling ExecuteReader().

    0 讨论(0)
  • 2021-02-07 12:24

    You're closing the connection rdr.Close(); and never re-opening it before calling ExecuteNonQuery().

    You don't actually need to close it at all if it's wrapped in a using as the call to Dispose() will automatically close the connection for you.

    0 讨论(0)
提交回复
热议问题