Am i disposing my ODBCConnection
I'm using a helper method like this:
private OdbcCommand GetCommand(string sql)
{
string conString = "blah";
var con = new OdbcConnection(conString);
var cmd = new OdbcCommand(sql, con);
return cmd;
}
Then i use it like this:
using (var cmd = GetCommand("select * from myTable")
{
cmd.connection.open();
using(var reader = cmd.ExecuteReader())
{
}
}
Here is a second example:
public static OdbcDataReader GetReader(string conString,string sql)
{
var cmd = GetCommand(conString, sql);
cmd.Connection.Open();
return cmd.ExecuteReader();
}
used like this:
using(var reader = GetReader("blah","select * from blah")
{
}
In these two cases, am i disposing of the connection and cmd objects? I think connection is not being disposed in the first, and n开发者_如何学Pythoneither connection nor cmd in the second, is that right?
Do i need to do i the long way to ensure correct disposal, or is there a shorter approach?
using (var con ...)
using (var cmd)
using (var reader)
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.
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'
using(var reader = cmd.ExecuteReader(CommandBehavior.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.
精彩评论