Note that deleting an instance of SqlDataReader using SqlCommand.ExecuteReader () will not close / delete the underlying connection.
There are two common patterns. Firstly, the reader opens and closes as part of the connection:
using(SqlConnection connection = ...) { connection.Open(); ... using(SqlCommand command = ...) { using(SqlDataReader reader = command.ExecuteReader()) { ... do your stuff ... } // reader is closed/disposed here } // command is closed/disposed here } // connection is closed/disposed here
Sometimes itβs convenient to have a way to access data, open a connection and return the reader. In this case, it is important that the returned reader is opened using CommandBehavior.CloseConnection, so closing / removing the reader will close the underlying connection. The template looks something like this:
public SqlDataReader ExecuteReader(string commandText) { SqlConnection connection = new SqlConnection(...); try { connection.Open(); using(SqlCommand command = new SqlCommand(commandText, connection)) { return command.ExecuteReader(CommandBehavior.CloseConnection); } } catch {
and the calling code just needs to recycle the reader like this:
using(SqlDataReader reader = ExecuteReader(...)) { ... do your stuff ... }
Joe Apr 13 '09 at 15:45 2009-04-13 15:45
source share