I am trying to understand DbConnection and DbCommand, and the proper way to dispose those objects after use.
Following is the code snippet I have.
By using “using statement” on DbConnection and DbCommand, would it be sufficient? I am trying to prevent possible memory leak.
2nd question,
Do I have to Dispose DbCommand object?
thanks a lot
DbProviderFactory fac = DbProviderFactories.GetFactory(this.DatabaseProviderName);
using (DbConnection dbConn = fac.CreateConnection())
{
dbConn.ConnectionString = this.ConnectionString;
using (DbCommand comm = fac.CreateCommand())
{
comm.CommandText = "select * from aTable";
comm.Connection = dbConn;
DataTable targetTable = new DataTable();
DbDataAdapter facDA = fac.CreateDataAdapter();
facDA.SelectCommand = comm;
facDA.Fill(targetTable);
//assuming Adapter would open / close connection (right assumption?)
//do something with the datatable
}
}
using
usingis the same as atry/finallyblock withdispose()called infinally.DbCommandshould be wrapped in ausingstatement as it implementsIDisposable.Note that
DbCommandis actually an abstract class so you will need to eitherIDbCommand)SqlCommand.DbConnectionis also an abstract class so you will need to do something similar as I have suggested above forDbCommandfor this too.The general recommendation is that if an object implements
IDisposable, it should be wrapped in ausingstatement such thatDispose()is called to free resources, even if an Exception is thrown within in the statement block. In your example then, a good practice would be to wrap each of the connection, command,DataTableandDbDataAdapterobjects in ausingstatement.