ASP.Net / ADO connection management

What is the best strategy for opening/reading from/closing connections in an ASP.net application? If you have code behind a page that pulls data from a DB, what happens when 2 users access that same code at the same time? Are 2 separate instances of your ado connection object created on the server?

What if you want to open a connection and use it across multiple pages? How would you go about that?
LVL 1
gallo47Asked:
Who is Participating?
 
dfiala13Connect With a Mentor Commented:
The best strategy is to open a connection, use it and close as soon as possible. .NET handles connection pooling for you (assuming you are always using the same connection string)

If you have code-behind in a page that does a database connection, you will have one instance of each page created and hence one connection object per page.  Two users, two pages, two connections. They are not shared among users.  As mentioned above .NET handles the pooling under the covers so the physcial connections made to the database are minimized.  As soon as you close a connection object , .NET throws the physical connection back into the pool for the next connection request.  To leverage this, it is important to not keep connections open for any longer than you need to. You definitely don't want to open a connection, read some data and wait for the user to update the data.  You get the data and close the connection. When the user submits their changes, open a connection, write to the db and close the connection.

I typically build a DataAccess class that handles creating connections and executing commands.  This is created and called either from an ASPX page or a middle-tier class.  But either way, it means I only have to write my database rotuines in one place and use them anywhere.  This keeps the page code simple and cuts down on cut-and-paste coding.
0
 
gallo47Author Commented:
Good answer. That's pretty much where my mind was heading but its great to have EE around to get the full scoop. Thanks!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.