Does ExecuteScalar close the connection automatically?
Asked
Active
Viewed 3,843 times
3 Answers
6
No, you need to explicitly open and close the connection when using ExecuteScalar().

DCNYAM
- 11,966
- 8
- 53
- 70
5
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;
}

Rodrick Chapman
- 5,437
- 2
- 31
- 32
-
this looks nice, but I can only develope against .NET 2.0 =) – Rookian Jul 12 '10 at 15:32
-
1@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 Jul 12 '10 at 15:38
3
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 Karo
- 17,924
- 4
- 40
- 58