I've been working on a web application in ASP.net. My application has several pages and all of them need to display tables that are populated by a database. Right now what I'm doing is, on each page, I'm opening a database connection, executing the query specific to that page, and closing the db connection. So this happens each time the user clicks a link to go to a new page or clicks a form control like the grid page.
I was wondering if this was a disaster from the performance point of view. Is there any better way to do this?
It should always be closed deterministically. The second and even more recommended way of doing the same thing is by wrapping the data access code in a " using " block. The using statement explicitly declares that we are using a disposable object for some time i.e. only till the using block ends.
SqlConnection Example Look at the following C# code. Using block is used to close the connection automatically. We don't need to call close () method explicitly, using block do this for ours implicitly when the code exits the block.
For the purpose of safe coding, you should always close database connections explicitly to make sure that the code was able to close itself gracefully and to prevent any other objects from reusing the same connection after you are done with it.
Answers. Yes. When the using block ends, the connection automatically closes (That is what IDisposable is for). So, do not close the connection explicitly.
Almost universally, database connections should be handled as follows: Open as late as possible, and close as soon as possible. Open and close for multiple queries/updates... don't think leaving it open saves you anything. Because connection pooling generally does a very good job for you of managing the connections.
It is perfectly fine to have a couple/few connections opened/closed in the production of a single page. Trying to keep a single connection open between page views would be quite bad... don't do that under any circumstances.
Basically, with connection pooling (enabled by default for almost all providers), "closing" a connection actually just releases it back to the pool to be reused. Trying to keep it open yourself will tie up valuable connections.
That is exactly how you want it to be. A database connection should only be opened when necessary and closed immediately after use.
What you may want to look at, especially if performance is a big issue for you, is caching. You may want to cache the entire page, or just parts of a page, or just the data that you would like displayed on your pages. You will save a lot of database trips this way, but you would have to now consider other things like when to update your cache, caching for different users, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With