关联的sqldatareader已打开! [英] An associated sqldatareader is already opened!

查看:45
本文介绍了关联的sqldatareader已打开!的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好

我有很多行代码,在不同的事件中使用了许多sqldatareader,但是,一旦单击按钮,就会出现错误消息

I have many lines of code, using many sqldatareaders in different events but, once I make a click on a button I get an error of

 关联的sqldatareader已打开,

 an associated sqldatareader is already opened, 

是否有代码可以遍历项目中的所有sqldatareader并像这样关闭它们?:

is there a code to loop through all sqldatareader in project and close them like this concept?:

foreach(当前项目中的sqldatareader r)

foreach(sqldatareader r in currentproject)

r.Close();

r.Close();

谢谢

推荐答案

不,除非您自己跟踪所有数据读取器.

Not unless you have kept track of all your data readers yourself.

但是我宁愿您需要从整体上了解您的应用程序设计.数据读取器不应在各处都保持打开状态.应该尽快打开,使用和关闭它们,因为打开时它们会耗尽连接.

But I rather think you need to take a look at your application design as a whole. Data readers should not be kept open all over the place. They should be opened, used and closed as soon as possible, because while open they are using up the connection.

例如

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{ 
   // Do something
}

reader.Close();

更好的是,最好将其放在try/finally块或"using"语句中:

Even better, this should preferably be inside try/finally block or a 'using' statement:

using(SqlDataReader reader = command.ExecuteReader())
{
  while (reader.Read())
   { 
      // Do something
   }
}; // implicitly closes reader


这篇关于关联的sqldatareader已打开!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆