gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 07:51:53 34 4
gpt4 key购买 nike

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/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com