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
2010-07-12 14:51:10
+1 for noting that ExecuteScalar is a method on an interface.
Rodrick Chapman
2010-07-12 15:15:15
+3
A:
No, you need to explicitly open and close the connection when using ExecuteScalar().
NYSystemsAnalyst
2010-07-12 14:55:01
+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
2010-07-12 15:11:57
@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
2010-07-12 15:38:59