Connection to database- how?

  • Thread starter Thread starter Ian
  • Start date Start date
I

Ian

Hi there,

I have just started learning c# and I have stored my connection string in
the web.config which I can read in my main program.

My question really is, should I open the database on every single page and
also close it too?

I presume I open it on Page Load but where should I close it... at the end
of page load or should I keep it open in the global.asa file?

I know this has something to do with connection pooling but didn't know how
the normal was for writing asp.net

Any ideas?

Thanks

Ian
 
Open your connection only when you need it, and close it as soon as you're
done with it. That may be on load, it may be on a button click.

If you use a DataAdapter, it will open and close it for you on .Fill. If you
use command.Executexxxx(reader, scalar) etc, then close it right after the
execute stateument unless you are using a datareader, at which point close
it after you use while dr.Reader (you may also want to set the
CommandBehavior to close).

HTH,

BIll
 
+1 to William's comments.


William Ryan eMVP said:
Open your connection only when you need it, and close it as soon as you're
done with it. That may be on load, it may be on a button click.

If you use a DataAdapter, it will open and close it for you on .Fill. If you
use command.Executexxxx(reader, scalar) etc, then close it right after the
execute stateument unless you are using a datareader, at which point close
it after you use while dr.Reader (you may also want to set the
CommandBehavior to close).

HTH,

BIll
 
Back
Top