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 neither 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)
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.