The second option is much better. You should open up a connection for
each function and close it as soon as possible. You will get the same
connection back from the pool 99.9% of the time. More importantly,
OTHER sessions will most likely get that SAME connection, meaning your
database is only seeing one connection. This is infinetly more
scalable.
Regardless of scalability, having one connection and just keeping it
open the whole time is not technically possible for any but trivial
applications, as you can only have one recordset open at a time per
connection. This means that while you are looping through a
datareader, you cannot run any other queries or get any other
datareaders using that connection. This seems like a big step
backwards from classic ADO, but in reality it is not. ADO had the
same limitation, it just opened up a second connection for you
automatically under the covers. The same total number of connections
open is the same, but in ado.net you are aware that you are using two
connections, so perhaps you can redisign code to work more
efficiently.
In my applicaitons I have a connect() function that creates and opens
then returns a connection. I call that at the beginning of each of my
data functions. Then if I am using a dataset, or doing an
executenonquery , I close right inside that funciton. If I am returning
a datareader outside of the function, I always use
CommandBehaviou r.CloseConnecti on and pass it out that way to minimize
impact on my connection pool.
" Bob" <bo*******@yaho o.com> wrote in message news:<Og******* ******@TK2MSFTN GP11.phx.gbl>.. .
In our new .NET web applications, we try to limit the use of SqlConnection
to just one instance per page, even if there are multiple accesses to
various queries. The thinking behind is that this reduces the need to
getting and returning connections to the pool repeatedly if a page has
multiple calls to the DB, and each one manages its own connection. However,
this does requires more deliberate coding, like calling the
SqlConnection.C lose() method in the page's Dispose() method so it's
garanteed that the connection is closed when the page processing is done,
and also is not closed too early. What I'm thinking is whether this is
actually necessary because passing the Connection object into child controls
becomes a pretty big hassle when there are several user controls or custom
controls on the page. If the connection pool management is very efficient
then opening and closing connections repeatly in the code (which is really
getting and returning connections to the pool) wouldn't be a big deal, and
keeping the code simple would be more important. Could anyone give some
suggestions?