我是否要处置我的 ODBCConnection
我正在使用这样的辅助方法:
private OdbcCommand GetCommand(string sql)
{
string conString = "blah";
var con = new OdbcConnection(conString);
var cmd = new OdbcCommand(sql, con);
return cmd;
}
然后我像这样使用它:
using (var cmd = GetCommand("select * from myTable")
{
cmd.connection.open();
using(var reader = cmd.ExecuteReader())
{
}
}
这是第二个例子:
public static OdbcDataReader GetReader(string conString,string sql)
{
var cmd = GetCommand(conString, sql);
cmd.Connection.Open();
return cmd.ExecuteReader();
}
像这样使用:
using(var reader = GetReader("blah","select * from blah")
{
}
在这两种情况下,我是否处理连接和 cmd 对象?我认为第一个连接没有被处理,第二个连接和 cmd 都没有被处理,对吗?
我是否需要走很长的路才能确保正确处置,还是有更短的方法?
using (var con ...)
using (var cmd)
using (var reader)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
简而言之,如果它有 Dispose,那么您应该调用它。您不能假设另一个对象会处理您为您传递的对象。
处置命令对象不会处置连接对象,因为在完成命令后您可以再次使用连接。处理掉每一个是最好的方法。
In short, if it has
Dispose
, then you should call it. You can't assume that another object will dispose of an object you pass it for you.Disposing the command object, will not dispose the connection object, because you can use the connection again after you are done with the command. Disposing of each is the best approach.
对于将 Reader 包装在 using 块中的两个示例,如果您使用接受 CommandBehavior 的覆盖并将其设置为“CloseConnection”,则将关闭与现有代码的连接,
请参阅 http://msdn.microsoft.com/en-us/library/s9bz2k02.aspx
Microsoft 知道在阅读器使用时连接必须保持打开状态,因此创建了关闭选项Reader 关闭时的连接。
您是正确的,在第二个示例中该命令没有被释放。
For both examples where you wrap your Reader in a using block, you will close the connection with the existing code IF you use the override that accepts a CommandBehavior and set it to 'CloseConnection'
see http://msdn.microsoft.com/en-us/library/s9bz2k02.aspx
Microsoft knows that the connection must remain open while the reader is consumed, and therefore created the option to close the connection when the Reader is closed.
You are correct that the command is not being Disposed in the second example.