Can anyone tell me what is the CommandBehavior.CloseConnection
and what is the use/benefit of passing this as a parameter in com.ExecuteReader(CommandBehavior.CloseConnection)
?
CloseConnection, which is a parameter of the ExecuteReader method. If we are using the CommandBehavior. CloseConnection, then we do not need to close the database connection explicitly because once we close the datareader object then it automatically closes the database connection as well.
Ultimately it is the Close method of the data reader that will close the connection, provided nothing has gone wrong before. If there is an exception that occurs inside ExecuteReader or any of its called methods, before the actual DataReader object is constructed, then no, the connection will not be closed.
You need an open connection while reading a data reader, and you want to close connections as soon as you can. By specifying CommandBehavior.CloseConnection
when calling ExecuteReader
, you ensure that your code will close the connection when it closes the data reader.
But you should already be disposing your connections immediately (not just closing them), in which case there's at best a marginal (almost certainly unmeasurable) benefit to doing this.
For example, this code closes its connection immediately (and performs whatever other work is required to dispose it), without specifying the command behavior:
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
// Do something with the rows
}
}
Use CommandBehavior.CloseConnection
in functions that create a connection but return a IDataReader
. Be very careful to Dispose()
of the IDbConnection
on exceptions only before the reader is created:
IDataReader ReadAll()
{
var connection = new SqlConnection(connectionString);
try
{
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "SELECT * FROM mytable";
var result = command.ExecuteReader(CommandBehavior.CloseConnection);
connection = null; // Don't dispose the connection.
return result;
}
finally
{
if (connection != null)
connection.Dispose();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With