开发者

ADO.NET: Does ExecuteScalar close the connection automatically?

开发者 https://www.devze.com 2023-01-07 07:33 出处:网络
Does 开发者_如何学运维ExecuteScalar close the connection automatically?No, you need to explicitly open and close the connection when using ExecuteScalar().You could create an overload using an extensi

Does 开发者_如何学运维ExecuteScalar close the connection automatically?


No, you need to explicitly open and close the connection when using ExecuteScalar().


You could create an overload using an extension method though I'm not sure if it's a good idea.

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


That depends.
One can write an implementation of IDbCommand that will close the connection.
But as far as I know the provided implementations does not close the connection.

0

精彩评论

暂无评论...
验证码 换一张
取 消