How to close the database connection before coming out of the function
Posted on 2005-03-31
I have a function of type DataReader and I'm getting the results of the function to Privatedatareader like
Private privateDataReader As OleDbDataReader
My function looks like this. I want to close the connection after I get the results to the above constant(PrivateDataReader). It goes to endfunction immediatly after return PrivateDataReader.
Public Function runDBDataReader(ByVal SQL As String) As OleDbDataReader
'Check to see if this object has already been disposed
If privateDisposedBoolean = True Then
Throw New ObjectDisposedException(privateModuleName, "This object has already been disposed. You cannot reuse it.")
'Set a new Connecton
privateConnection = New OleDbConnection(privateConnectionString)
'Set a new Command that accepts an SQL statement and the connection.
'The command.commandtype does not have to be set since it defaults to text
privateCommand = New OleDbCommand(SQL, privateConnection)
'We need to open the connection for the DataReader explicitly
'Run the Execute Reader method of the Command Object
privateDataReader = privateCommand.ExecuteReader
Catch ExceptionObject As Exception
'Any exception will be logged through our private logexception function
'If an exception occurs, close the connection now!
'The exception is passed back to the calling code, with our custom message and specific exception information
Throw New Exception(privateExceptionMessage, ExceptionObject)