Question

In java, you cannot access the ResultSet once the Statement is closed, although many times you get a small amount of fetched data making it appear to be open. But in general it is against the API rules.

But in OLEDB, I'm wondering if the same rule applies with the Command and the reader. For instance, is the following code 100% safe? Will the SQL fetch cursor remain open even though command is disposed?

public OleDbDataReader ExecuteReader(string sql, OleDbConnection connection)
{
  using (OleDbCommand command = CreateCommand(sql, connection))
  {
     return command.ExecuteReader();
  }
}
Was it helpful?

Solution

This is not recommended at all. Why would you do it?

When the Command is Disposed (this happens when the execution leaves the using block), the connection won't be closed, so you can probably keep using the DataReader.

However this is a very bad idea:

  • you can't get sure that the connection will be closed, because it depends on external code.

  • this can put locks in the DB so that you'll have contention problems.

  • the connection used by your Reader keeps "busy" so that it cannot be reused.

You should always make sure that the reader, and then the related connection, are closed. With this design you should rely on the user of the returned DataReader to Close the reader and the connection. Or at least the reader, if you use the SqlCommand.ExecuteReader overload that receives a CommandBehavior in which you can set CloseConnection, so that the conenction will be closed automatically when the reader is closed.

But I insist, you should never keep a DataReader open for too long. The datareader should be iterated and closed as soon as possible. It's available to avoid the overhead of transferring data to DataTables, and the using it. I.e. when you bind to a control, like a DataGridView, you can bind the data directly to the control avoiding the intermediate use of a DataTable, which requires extra processing time and memory (data to datatable and then to control, instead of data directly from datasource to control).

So, perhaps you can do that, but deefinitely, you shouldn't!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top