views:

54

answers:

3

Does ExecuteScalar close the connection automatically?

+2  A: 

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.

Itay
+1 for noting that ExecuteScalar is a method on an interface.
Rodrick Chapman
+3  A: 

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

NYSystemsAnalyst
+1  A: 

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)
{
    object obj = Command.ExecuteScalar();        

    if(CloseConnection && Command.Connection.State != ConnectionState.Closed)
        Command.Connection.Close();    

    return obj;

}
Rodrick Chapman
this looks nice, but I can only develope against .NET 2.0 =)
Rookian
@Rookian, Since extension methods are just methods on a static class you could always call the method like so: Helper.ExecuteScalar(IDbCommandInstance, true);
Rodrick Chapman

related questions