Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will dbCommand.Close() close the connection as well?

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;
            }
        }
like image 242
J.W. Avatar asked Sep 14 '09 19:09

J.W.


People also ask

Is it necessary to close DB connection?

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.

How do I cancel DbConnection?

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.


2 Answers

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.

like image 184
Satya.JS Avatar answered Sep 21 '22 11:09

Satya.JS


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.

like image 43
Adam Robinson Avatar answered Sep 18 '22 11:09

Adam Robinson