重新打开SqlDataReader
我的代码抛出错误
阅读器关闭时调用 Read 的尝试无效。
我正在使用 SqlDataReader 从数据库读取值,这就是我的代码:
while (rd.Read())
{
string stateincharge = rd["stateincharge"].ToString();
string email = rd["email"].ToString();
cmd.Dispose();
rd.Close();
cmd = con.CreateCommand();
cmd.CommandText = "str_procedure";
cmd.Parameters.AddWithValue("@stateincharge", stateincharge);
cmd.CommandType = CommandType.StoredProcedure;
ad.SelectCommand = cmd;
ad.Fill(ds);
count = ds.Tables[0].Rows.Count;
DataTable dt = new DataTable();
}
这在 ASP.NET 代码隐藏中的循环中运行。
我的问题是,由于显示错误,我认为我需要关闭 SqlDatReader。
如何在 while 循环结束时再次打开 sqlDataReader?
My code throws the error
Invalid attempt to call Read when reader is closed.
I'm using SqlDataReader to read values from database, and that is my code:
while (rd.Read())
{
string stateincharge = rd["stateincharge"].ToString();
string email = rd["email"].ToString();
cmd.Dispose();
rd.Close();
cmd = con.CreateCommand();
cmd.CommandText = "str_procedure";
cmd.Parameters.AddWithValue("@stateincharge", stateincharge);
cmd.CommandType = CommandType.StoredProcedure;
ad.SelectCommand = cmd;
ad.Fill(ds);
count = ds.Tables[0].Rows.Count;
DataTable dt = new DataTable();
}
This runs in a loop in ASP.NET code-behind.
My problem is that I think I need to close SqlDatReader because of an error shown.
How can I again open sqlDataReader at end of the while loop?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须删除关闭读取器的行
rd.Close();
因为您要在 while 循环内关闭读取器,然后尝试再次访问读取器。另外,我认为如果您使用新的 SQL 命令和新适配器,您将不会收到此错误。You have to remove the line that closes the reader
rd.Close();
because you are closing the reader inside the while loop then you try to access the reader again. Also, I think if you used a new SQL command and new adapter you will not receive this error.每个连接最多可以有一个活动命令(其中包括“响应”,即阅读器)。您正在尝试对数据库进行嵌套调用,这要求您在循环之前完全加载数据(例如加载到
DataTable
中),或者使用第二个连接来进行嵌套调用到str_procedure
。Each connection can have at most one active command (which includes the "response", that is, the reader). You're trying to do a nested call to the DB and this requires that you either load the data completely (for instance into a
DataTable
) before looping, or that you uise a second connection for the nested calls tostr_procedure
.