Software Technology Tips

In some situations we feel the need to close a SQL connection object immediately after the SQL query operation with a associated reader is complete. We can not close the connection before we complete all the operations related to the reader. Also we need to close the connection immediately after we finish the use of reader object.
In .NET we have a mechanism to achieve this objective using an overloaded form of ExecuteReader() function with an extra argument as shown below:
OleDbDataReader oReader = oCommand.ExecuteReader(CommandBehavior.CloseConnection);
The argument "CommandBehavior.CloseConnection" will specify that the connection object will close automatically when we close the Reader object.
The sample code is given below:

OleDbConnection connectionObj = new OleDbConnection(connectionString);
OleDbCommand commandObj = new OleDbCommand();
OleDbDataReader readerObj = null;
commandObj = new OleDbCommand(sqlQuery, connectionObj);
readerObj = commandObj.ExecuteReader(CommandBehavior.CloseConnection);
Now when we close the Reader object then the Connection object will close automatically.

Related Tags:

ADO.NET, .NET, Database

Author: Amit Mohapatra


Let us Connect!

Awards and Achievements

Red Herringcolor DeloitteFast50 DB ZInnov1   Nascome  DB Stpi

This site uses cookies. We respect your privacy.copyright (c) Mindfire Solutions 2007-2015. Login