.net SqlCommand.ExecuteReader 是否关闭连接?
在这句话中:
myCommand.ExecuteReader(CommandBehavior.CloseConnection)
如果出现异常,是否会关闭连接?
In this sentence:
myCommand.ExecuteReader(CommandBehavior.CloseConnection)
does it close connection in case of exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
执行“正常”查询的最安全方法是
可以在此代码之外捕获异常。
The safest way to do a "normal" query is
Exceptions can be caught outside this code.
该命令有多种可能出错的方式。
最终,数据读取器的 Close 方法将关闭连接,前提是之前没有出现任何问题。
如果在构造实际的 DataReader 对象之前,在 ExecuteReader 或其任何调用的方法内部发生异常,则不会,连接不会关闭。
如果出现异常,我不相信它会关闭连接。
There are plenty of ways that the command can go wrong.
Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before.
If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.
In case of an exception, I wouldn't trust it to close the connection.
这取决于异常发生在哪里!
如果你的 try catch 结构正确,那就没问题了。
例如:
如果 myCommand.ExecuteReader(CommandBehavior.CloseConnection) 行失败(也许数据库已关闭?),则无法以编程方式关闭连接。
It depends where the exception occurs!
If you structure your try catch correctly, it will be fine.
For example:
If the line: myCommand.ExecuteReader(CommandBehavior.CloseConnection) fails (perhaps the database has gone down?) then the connection cannot be closed programmatically.