oracle 如何在 .NET 中关闭 OracleConnection
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/698397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I close an OracleConnection in .NET
提问by Mike Comstock
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?
要关闭连接或 Oracle,我是否必须调用 command.Dispose()、connection.Dispose() 或两者?
Is this good enough:
这是否足够好:
using(connection)
{
OracleDataReader reader = cmd.ExecuteReader();
// whatever...
}
回答by John Saunders
using (OracleConnection connection = new OracleConnection(connectionString))
{
using (OracleCommand command = new OracleCommand(sql, connection))
{
using (OracleDataReader reader = cmd.ExecuteReader())
{
}
}
}
If it implements IDisposable, and if you create it, then put it in a using block.
如果它实现了 IDisposable,并且如果你创建了它,那么把它放在一个 using 块中。
回答by Russ
Both answers are pretty much on target. You always want to call .Dispose() on any IDisposeable object. By wrapping in a "using" you tall the compiler to always impliment a try/finialy block for you.
这两个答案都非常符合目标。您总是想在任何 IDisposeable 对象上调用 .Dispose() 。通过包装在“使用”中,您可以使编译器始终为您实现 try/finialy 块。
1 point of note, if you want to avoid the nesting, you can write the same code like this:
1点注意,如果你想避免嵌套,你可以像这样编写相同的代码:
using (OracleConnection connection = new OracleConnection(connectionString))
using (OracleCommand command = new OracleCommand(sql, connection))
using (OracleDataReader reader = cmd.ExecuteReader())
{
// do something here
}
回答by J.W.
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.
这已经足够好了。using 语句将包装 dispose 语句,因此即使抛出异常,您也是安全的,这是我处理资源的首选方式。
using(OracleConnection connection = new OracleConnection(connectionString); )
{
//Create a command object
using(OracleCommand command = new OracleCommand(sql, connection))
{
using(OracleDataReader reader = cmd.ExecuteReader())
{
}
}
// whatever...
}
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.
我认为通过使用“使用”,你会要求编译器注入一个 try ... finally 块,在 finally 块中,它会为你关闭一次性对象。
回答by Aaron Daniels
using
will ensure your connection is closed. You could also pass in CommandBehavior.CloseConnection
to your command's ExecuteReader
method to close it before Dispose
is called.
using
将确保您的连接已关闭。您还可以传入CommandBehavior.CloseConnection
您的命令的ExecuteReader
方法以在Dispose
调用之前关闭它。