【问题标题】:ADO.NET: Does ExecuteScalar close the connection automatically?ADO.NET:ExecuteScalar 会自动关闭连接吗?
【发布时间】:2010-07-12 14:47:19
【问题描述】:

ExecuteScalar 会自动关闭连接吗?

【问题讨论】:

    标签: ado.net executescalar


    【解决方案1】:

    不,您需要在使用 ExecuteScalar() 时显式打开和关闭连接。

    【讨论】:

      【解决方案2】:

      您可以使用扩展方法创建重载,但我不确定这是否是个好主意。

      public static object ExecuteScalar(this IDbCommand Command, bool CloseConnetion)
      {
      
          (if Command == null)
              throw new NullReferenceException();
      
          object obj = null;
      
          try
          {
            obj = Command.ExecuteScalar();        
          }
          finally
          {
            if(CloseConnection && Command.Connection.State != ConnectionState.Closed)
              Command.Connection.Close();    
          }
      
          return obj;
      }
      

      【讨论】:

      • 这看起来不错,但我只能针对 .NET 2.0 进行开发 =)
      • @Rookian,由于扩展方法只是静态类上的方法,您始终可以像这样调用该方法:Helper.ExecuteScalar(IDbCommandInstance, true);
      【解决方案3】:

      这取决于。
      可以编写IDbCommand 的实现来关闭连接。
      但据我所知,提供的实现不会关闭连接。

      【讨论】:

      • +1 表示 ExecuteScalar 是接口上的一个方法。
      猜你喜欢
      • 2021-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-02
      • 1970-01-01
      • 2012-12-11
      • 2017-05-24
      • 1970-01-01
      相关资源
      最近更新 更多