问题描述
你好
我有很多行代码,在不同的事件中使用了许多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();
谢谢
推荐答案
但是我宁愿您需要从整体上了解您的应用程序设计.数据读取器不应在各处都保持打开状态.应该尽快打开,使用和关闭它们,因为打开时它们会耗尽连接.
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已打开!的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!