我有以下ado.net代码,如果我已经使用使用来包装我的DBCommand,是否必须显式关闭下面的连接?

谢谢,

       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;
            }
        }

最佳答案

是的,如果包裹在using块中的只是DbCommand,那么您将必须像当前在代码中那样显式关闭DbConnection。但是,只需调用Dispose就足够了。您无需同时调用CloseDispose

关于asp.net - dbCommand.Close()也会关闭连接吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1423391/

10-13 09:35