c# - ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态是关闭的

标签 c# asp.net sql

ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态为关闭。

我在这里做错了什么?我假设您可以重用该连接?

感谢您的帮助!

using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["LocalSqlServer"].ToString()))
{
    cn.Open();

    // If we are reverting to an old type
    if (pageAction == "revert")
    {
        debug.Text = "FLAG 1";

        // Get the revert ID
        int revertingID = int.Parse(Request.QueryString["revID"]);
        bool rowsReturned = false;

        debug.Text = "FLAG 2 - " + revertingID.ToString();

        // 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();
        }

        debug.Text = "FLAG 3 - " + rowsReturned.ToString();

        // Set new active and reset others
        if (rowsReturned == true)
        {
            using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 1 WHERE ID = " + revertingID, cn))
            {
                cmd.ExecuteNonQuery();
            }
            using (SqlCommand cmd = new SqlCommand("UPDATE tblSiteSettings SET isActive = 0 WHERE ID <> " + revertingID, cn))
            {
                cmd.ExecuteNonQuery();
            }
        }
        //debug.Text = "FLAG 4 - ";
    }

最佳答案

你的问题是:

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

如果您想在“摆脱”它之前再次使用该连接,您应该只调用 cmd.ExecuteReader()'。如果您想了解 CommandBehaviour.CloseConnection 部分的作用/含义,请参阅 SqlCommand.ExecuteReader 的文档是一个不错的选择。还有文档告诉您 CommandBehaviour enumeration 的所有可能值是什么是。本质上,CommandBehaviour.CloseConnection 执行以下操作:

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

如果您没有特别需要指定 CommandBehaviour,则可以指定 CommandBehaviour.Default,或者根本不指定。 CommandBehaviour.Default 是:

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().

关于c# - ExecuteNonQuery 需要一个打开且可用的连接。连接的当前状态是关闭的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3548056/

相关文章:

c# - 使用什么设计模式来验证数据和创建对象

c# - 对 Nullable<T> 约束的困惑

c# - 如何使用正则表达式在C#中查找和替换“@@ word @@”?

c# - 无法为表中的标识列插入显式值

javascript - 如何在 page_load() 之前使用 javascript 填充 html 元素?

c++ - 完全面向对象的 C++ SQL 包装器?

c# - 使用 XmlDocument 操作 SSIS 包

c# - Response.Redirect 结果在 "Object moved to here"

java - 我如何使用不同版本的java

mysql - 创建13行31列的表结构