代码之家  ›  专栏  ›  技术社区  ›  J.W.

dbCommand.Close()是否也会关闭连接?

  •  9
  • J.W.  · 技术社区  · 15 年前

    我有以下ado.net代码,如果我已经使用 使用

    谢谢

           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;
                }
            }
    
    4 回复  |  直到 15 年前
        1
  •  5
  •   Adam Robinson    15 年前

    是的,如果你把所有的东西都包在 using 街区是最重要的 DbCommand 那你呢 必须显式关闭 DbConnection Dispose . 你不需要两个都打电话 Close .

        2
  •  3
  •   Satya.JS    15 年前

    http://www.willydev.net/descargas/WillyDev_EntLib_TestGuide.pdf

    应用程序块在完成数据库连接后关闭它们。例如,ExecuteOnQuery方法的实现包括一个using语句。using语句获取资源、执行语句并处置资源。在本例中,资源是数据库连接。对于ExecuteReader方法,应用程序块使用Command-Behavior.CloseConnection方法在读取器关闭后关闭连接。

        3
  •  1
  •   eduardobr    12 年前

    这篇文章很旧,但我的回答是,如果我们将此块与EnterpriseLibrary一起使用,我确信连接是关闭的(代码块中的类和方法名称让我想到了这一点)。 回答问题的人应该明确地考虑我们是否在谈论EngBrimiSrabor。

        4
  •  -1
  •   cptScarlet    15 年前

    不,你没有。

    一旦点击using块的末尾,就会为您调用dispose。