I have created the following method:
public System.Data.OleDb.OleDbDataReader GetReader(string sqlQuery)
{
System.Data.OleDb.OleDbConnection myConnection = new System.Data.OleDb.OleDbConnection();
LoadConnectionStrings();
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
System.Data.OleDb.OleDbCommand myCommand = new System.Data.OleDb.OleDbCommand(sqlQuery, myConnection);
System.Data.OleDb.OleDbDataReader myReader = null;
myReader = myCommand.ExecuteReader();
return myReader;
}
Several thousand lines of code rely on it, and i guess i wasn’t really thinking when i implemented it…
Anyway,. If i retrieve a reader this way i have no way of closing the connection, and if i close the connection before the reader has called the read() method it will blow up when it goes to read and say that the connection to the database needs to be Open.
The question is, how can i close connection from previous bodies of code? Or all connections in general maybe..
From what I’ve read here if you don’t specifically call ‘close()’ it doesn’t get closed, and if you’re using an access 2003 file it kind of leaves you in a world of hurt
In that scenario, the connection needs to stay open for the reader to work – however, there is an overload to ExecuteReader that lets you specify a flag for the reader to close the connection when the reader is closed:
This allows a caller to use:
And the connection will be closed cleanly when the caller is done with the reader.