如何在 .NET 中关闭 OracleConnection
假设我有这两个对象:
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand command = new OracleCommand(sql, connection);
要关闭连接或 Oracle,我是否必须调用 command.Dispose()、connection.Dispose() 或两者都调用?
这是否足够好:
using(connection)
{
OracleDataReader reader = cmd.ExecuteReader();
// whatever...
}
Say I have these two objects:
OracleConnection connection = new OracleConnection(connectionString);
OracleCommand command = new OracleCommand(sql, connection);
To close the connection or Oracle, do I have to call command.Dispose(), connection.Dispose(), or both?
Is this good enough:
using(connection)
{
OracleDataReader reader = cmd.ExecuteReader();
// whatever...
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果它实现了 IDisposable,并且您创建了它,则将其放入 using 块中。
If it implements IDisposable, and if you create it, then put it in a using block.
这两个答案都非常符合目标。 您几乎总是想在任何 IDisposeable 对象上调用 .Dispose()。 通过包装“using”,您可以告诉编译器始终为您实现 try/finialy 块。
1 注意点,如果你想避免嵌套,你可以编写相同的代码,如下所示:
Both answers are pretty much on target. You almost always want to call .Dispose() on any IDisposeable object. By wrapping in a "using" you tell the compiler to always implement a try/finialy block for you.
1 point of note, if you want to avoid the nesting, you can write the same code like this:
这已经足够好了。 using 语句将包装 dispose 语句,因此即使抛出异常,您也是安全的,这是我处置资源的首选方式。
我认为通过使用“using”,您要求编译器注入一个 try ...finally 块,并在finally块中,它将为您关闭一次性对象。
This is good enough. using statement will wrap the dispose statement, so even if the exception is thrown, you are safe, it's my preferred way to dispose the resource.
I think by use "using", you are ask the compiler to inject a try ... finally block , and in finally block, it will close the disposable object for you.
using
将确保您的连接已关闭。 您还可以将CommandBehavior.CloseConnection
传递给命令的ExecuteReader
方法,以在调用Dispose
之前将其关闭。using
will ensure your connection is closed. You could also pass inCommandBehavior.CloseConnection
to your command'sExecuteReader
method to close it beforeDispose
is called.