Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ADO.NET: Does ExecuteScalar close the connection automatically?

Does ExecuteScalar close the connection automatically?

like image 241
Rookian Avatar asked Jan 22 '26 00:01

Rookian


2 Answers

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

like image 181
DCNYAM Avatar answered Jan 26 '26 22:01

DCNYAM


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;
}
like image 29
Rodrick Chapman Avatar answered Jan 26 '26 23:01

Rodrick Chapman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!