DataReader and DB connection closing?

R

rockdale.green

I am using Microsoft.Practices.Enterprise.Library

When I use IDataReader I saw this line
"It is the responsibility of the caller to close the connection and
reader when finished."

I was wondering if I close the DataReader do I automatic ally close the
Connection? If not , how can I close the Connection outside the
ExecuteReader function?

I code snippet is like following:

------------------------------------------------
IDataReader oDr =null;

Database db = DatabaseFactory.CreateDatabase();

string sqlCommand = "my_stored_proc";
DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand);


oDr = db.ExecuteReader(dbCommand);


/*DO SOMETHING WITH oDR*/


/*I close the DataReader here, do I need to close connection also?*/
oDr.Close();
 
M

Miha Markic [MVP C#]

Hi,

You can specify CommandBehaviour.CloseConnection in ExecuteReader
(connection will be closed on oDr.Close()) or you have to manually close
associated connection.
And make sure you use try/finally or using construct to enforce disposing of
reader.
 
G

Guest

Use [using] statement to close the DataReader. When the using statement's
block completes, the DataReader is closed, closing the connection with it.

// Using "using" will cause both the DataReader and connection to be
// closed. (ExecuteReader will close the connection when the
// DataReader is closed.)
using (IDataReader dataReader = db.ExecuteReader(cmd))
{
while (dataReader.Read())
{
...
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top