Hi
I would like to open a db connection and then pass the same to all my sql
commands across various pages. Is there a way to implement this?
You can't do that since an SqlDataReader has the restriction of only
one open datareader at a time against the same SqlConnection.
So you need to have one connection for every page hit. (unless you
want to create your own lock logic and risc that users are being cued
up and everything goes DOWN in speed)
What you can do is to create one SqlConnection in the OnInit and then
do a dispose on that SqlConnection in the UnLoad of your page!
Then you'd inherit from your own WebPageClass which in turn inherit
from WebPage in ASP.NET!
Then you'd create a protected get only property in that middle class
which would make that SqlConnection accessible for you from "all over"
the place!
But...!
Obviously you should never though think about something as tiny as a
SqlConnection in your PAGE logic, your PAGE should use a "controller"
layer (read up on MVC, Model View Controller) which in turn could be
accessing its data over an analog TELEPHONE for all you care in your
View layer (ASP.NET)
If you sprangle your page with stuff like SqlConnection you can bet
your life on that the customer is gonna come demanding that you port t
to "oracle" or "xml, object based databases" or "something other new
and shiny technology"...
So to force encapsulation, singularity, coherence and in general terms
an otherwise nice day
![Wink ;) ;)](/styles/default/custom/smilies/wink.gif)
Read up on MVC and create a Facade class which you make accessible
through a Singleton which hides away stuff like "SqlCommand" and
"SqlConnection" etc...
Then if you'd want to be REALLY advanced you could also depend upon
stuff like an IDbConnection and create a Factory Method and an
Abstract Factory etc to create your IDbConnection...
Though the PERFECT solution is obviously to ditch everything I've said
and go out and use an ORM tool like for instance nHibernate or
something...
PS!
I never thought I'd have so much to say about such a small question...
..t