When to open and close database in web (ASP.NET) applications?

Posts   
 
    
clint
User
Posts: 150
Joined: 15-Nov-2005
# Posted on: 24-Jan-2012 17:59:47   

I'm a newbie when it comes to writing web applications.

When making Windows desktop applications, we would always open a database connection at the start of the application, keep it open the entire time the application is running, and then close it when the application closes.

I've read that when making web applications, you should only open a database connection when you actually need it and close it immediately after you no longer need it.

So I wrote a bunch of "manager" classes that are used to Create, Update, Delete, and Retrieve entities. Each of those operations open and close the database connections. However, I do have a transaction scope class I made that allows the connection to stay open if the database operation is part of a transaction.

Does it hurt performance to keep opening and closing database connections?

Would it be desirable to open the database connection at the the start of a page load event and close it at the end so that all database operations done in that time use the same connection?

Thanks in advance for any guidance.

Walaa avatar
Walaa
Support Team
Posts: 14983
Joined: 21-Aug-2005
# Posted on: 25-Jan-2012 09:08:50   

Does it hurt performance to keep opening and closing database connections?

ONly if youare using a database that doesn't support connection pooling.

Would it be desirable to open the database connection at the the start of a page load event and close it at the end so that all database operations done in that time use the same connection?

Try to do all your database operations in one method, there you can use one connection, and make sure to do everything inside a using block, or a Try Catch Finalize block, to make sure you close (dispose) the connection. I don't recommend using page events for that matter.