Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to close connection/datareader when using SqlDataSource or ObjectDataSource

during beta testing we discovered connection pooling error messages . Therefore I have been going through the code and closing down the SqlDataReader objects wherever they have been left unclosed. What I need to know is how to close a datareader (or if there is a need at all to close) that is specified in the SelectStatement attribute of the SqlDataSource or ObjectDataSource tags. Could there be connection leak if they are not handled?

Thanks in advance !

like image 218
Aamir Avatar asked Oct 20 '08 18:10

Aamir


People also ask

Does closing DataReader close connection?

Using the Close() method of the data provider's Connection object adds or returns the connection to the connection pool. Remember, however, that closing a connection automatically closes all DataReader objects associated with the connection.

Can I Close DataReader by closing SqlCommand?

The following example creates a SqlConnection, a SqlCommand , and a SqlDataReader. The example reads through the data, writing it out to the console window. The code then closes the SqlDataReader. The SqlConnection is closed automatically at the end of the using code block.

Is it necessary to manually close and dispose of SqlDataReader?

You don't need the . Close() statement in either sample: it's handled by the . Dispose() call.


1 Answers

I tend to use the "using" keyword, especially when dealing with opening and closing connections to a database. "using" is a shortcut to the Dispose pattern - here is a link to the MSDN writeup, and here is a link to a useful blog entry with an overview.

like image 192
Gunny Avatar answered Nov 14 '22 23:11

Gunny