Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use/advantage of using CommandBehavior.CloseConnection in ExecuteReader()

Tags:

c#

ado.net

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)?

like image 851
Vijjendra Avatar asked Apr 16 '11 20:04

Vijjendra


People also ask

What is 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.

Does ExecuteReader close connection?

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.


2 Answers

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
    }
}
like image 117
Jeff Sternal Avatar answered Oct 04 '22 02:10

Jeff Sternal


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();
    }
}
like image 20
Bruno Martinez Avatar answered Oct 04 '22 02:10

Bruno Martinez