gpt4 book ai didi

c# - 无法摆脱错误 "There is already an open DataReader associated with this Command which must be closed first"

转载 作者:搜寻专家 更新时间:2023-10-30 20:01:53 25 4
gpt4 key购买 nike

我正在从同一个数据库的四个不同表中提取数据,并试图将这些数据合并到一个 HTML 对象中。问题是我不断收到上面的“打开 DataReader”异常。

我尝试过的事情:

  • 在每个 if(reader.HasRows) block 之后用 reader.Close() 关闭阅读器
  • 在本地声明 SqlCommandSqlDataReadertry/catch
  • 在每个关闭阅读器的 try/catch 末尾添加一个 finally 语句(这个提示说 reader 变量没有尚未初始化)

以上均无效。我发现的所有解决方案都说要使用 MultipleActiveResultSets,但我实际上并不想要多个结果集。

在这种情况下可以使用哪些最佳做法?用四个不同的名称声明四个不同的阅读器变量,reader1、reader2 等?

编辑

这是我正在做的经过清理和缩短的版本

string connectionString = ConfigurationManager.ConnectionStrings["database"].ToString();
DataTable dt = new DataTable();
SqlCommand cmd;
SqlDataReader reader;
SqlConnection conn;

using (conn = new SqlConnection(connectionString))
{
try
{
conn.Open();
cmd = new SqlCommand("SELECT * FROM [table-one]", conn);
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
// Get a temporary copy of the data in a data table
dt.Load(reader);

// Do database things on table-one
}
}
catch (Exception ex)
{
// Exception caught
ThrowException(ex);
}

try
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [table-two] WHERE UserID = @uID", conn);
cmd.Parameters.Add(new SqlParameter("uID", User_ID));
SqlDataReader reader = cmd.ExecuteReader();

if (reader.HasRows)
{
// Get a temporary copy of the data in a data table
dt.Load(reader);

// Do database things on table-two
}
}
catch (Exception ex)
{
// Exception caught
ThrowException(ex);
}

最佳答案

取而代之的是:

    cmd = new SqlCommand("SELECT * FROM [table-one]", conn);
reader = cmd.ExecuteReader();
if (reader.HasRows)
{
// Get a temporary copy of the data in a data table
dt.Load(reader);

// Do database things on table-one
}

尝试:

using (cmd = new SqlCommand("SELECT * FROM [table-one]", conn))
{
using (reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
// Get a temporary copy of the data in a data table
dt.Load(reader);
}
}
}

// Do database things on table-one

即在执行任何更多数据库操作之前关闭/处理每个读取器。

关于c# - 无法摆脱错误 "There is already an open DataReader associated with this Command which must be closed first",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23503475/

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