我正在从同一个数据库的四个不同表中提取数据,并试图将这些数据合并到一个 HTML 对象中。问题是我不断收到上面的“打开 DataReader”异常。
我尝试过的事情:
- 在每个
if(reader.HasRows)
block 之后用reader.Close()
关闭阅读器 - 在本地声明
SqlCommand
和SqlDataReader
到try/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/