I have the following ado.net code, if I already use using to wrap my DBCommand, do I have to close the underneath connection explicitly?
Thanks,
public static void ExecuteSQL(int Id)
{
Database db;
const string sqlCommand = "Stored Procedure Name";
try
{
db = DatabaseFactory.CreateDatabase();
using (DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand))
{
db.AddInParameter(dbCommand, "p_Id", DbType.Int32, Id);
db.ExecuteNonQuery(dbCommand);
**//do I have to close connection explicitely here??**
if (dbCommand.Connection.State != ConnectionState.Closed)
{
dbCommand.Connection.Close();
}
dbCommand.Connection.Dispose();
}
}
catch (Exception ex)
{
Logger.Log.Error(ex.StackTrace, ex);
throw;
}
}
Relying on the garbage collection, especially in database programming, is a very poor programming practice. You should make a habit of always closing the connection with the close() method associated with connection object. To ensure that a connection is closed, you could provide a 'finally' block in your code.
If the DbConnection goes out of scope, it is not closed. Therefore, you must explicitly close the connection by calling Close or Dispose , which are functionally equivalent. If the connection pooling value Pooling is set to true or yes , this also releases the physical connection.
http://www.willydev.net/descargas/WillyDev_EntLib_TestGuide.pdf
The application block closes the database connections after it is finished with them. For example, the implementation of the ExecuteNonQuery method includes a using statement. The using statement obtains resources, executes a statement, and disposes of the resources. In this case, the resource is the database connection. In the case of the ExecuteReader method, the application block uses the Command-Behavior.CloseConnection method to close the connection after the reader closes.
Yes, if all you have wrapped in the using
block is the DbCommand
, then you will have to explicitly close the DbConnection
, as you currently do in your code. It is sufficient, however, simply to call Dispose
. You do not need to call both Close
and Dispose
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With