4

The typical query execution pattern I inherited is like so:

using (IDataReader r = query.ExecuteReader())
{
  while (r.Read())
  {
    // etc.
  }
}

Is query.Connection left open after the using block is exited?

svidgen
  • 13,744
  • 4
  • 33
  • 58

2 Answers2

6
ExecuteReader(CommandBehavior.CloseConnection)

This will close the connection when the datareader has it's close() method called (which occurs when the dispose() method is called through usage of the using block.

Ideally, you would use a using block with your SqlConnection object as well (or call dispose() manually inside a finally block), not just to close the connection, but also to release the resources.

Brad M
  • 7,857
  • 1
  • 23
  • 40
5

No; the connection will not be closed until you dispose the connection.

However, if you pass CommandBehavior.CloseConnection, the connection will be closed.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • is it ok to put a `r.Close();` after the `while {}` instruction? – DanielV Aug 18 '15 at 12:17
  • found it [Retrieving Data Using a DataReader (ADO.NET)](https://msdn.microsoft.com/en-us/library/haa3afyz(VS.100).aspx) silly question though – DanielV Aug 18 '15 at 12:22