C# SqlDataReader 关闭方法
以下哪种方法更适合关闭 SqlDataReader:
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
}
reader.Close();
reader.Dispose();
或者
SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
}
还有其他进一步的关闭方法?
Which of these methods is better for closing SqlDataReader:
SqlDataReader reader = comm.ExecuteReader();
while (reader.Read())
{
}
reader.Close();
reader.Dispose();
or
SqlDataReader reader = comm.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
}
or there are another further closing methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
处理此问题的正确方法是使用
using
语句:这样可以正确处理对象(并且不需要调用
Close()
)。The correct way of handling this is the
using
statement:This way the object gets disposed correctly (and you don't need to call
Close()
).根据我的经验,
using
语句是这种情况下的最佳实践。即使内部某处发生异常,它也确保连接正确关闭。当然,您可以使用
try { } finally { }
执行相同的操作,这就是using
语句在内部执行的操作。我发现养成始终通过using
语句处理读取器的习惯通常是一个好主意,以避免泄漏连接的可能性。A
using
statement is the best practice in such situations from my experience. It makes sure the connection is properly closed even if an exception happens somewhere inside.Of course you could do the same with a
try { } finally { }
, which is what theusing
statement does internally. I found it's generally a good idea to get in the habit of always handling readers via theusing
statement to avoid the possibility of leaked connections.如果您在一个方法中使用 reader,则使用第一种情况;如果您将 reader 作为返回值传递(不在一个范围内),则使用第二种情况。
Use first scenario if you work with reader within one method and second one if you pass reader as return value (not within one scope).
您需要的文档是这个: http:// /msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx
引用:“当您使用 SqlDataReader 来使用关联的数据时,必须显式调用 Close 方法用于任何其他目的的 SqlConnection。”
the doc you need is this one: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.close.aspx
To quote: "You must explicitly call the Close method when you are through using the SqlDataReader to use the associated SqlConnection for any other purpose."