Wednesday, March 21, 2012

Newbie Q regarding opening a connection to a database

Hello, Im new with databases.

I know that opening a connection to a DB is expensive. Usually I write a method that opens a connection to the DB then I execute a query and then close the connection. Pretty standard.

OK, so how do I handle opening connections to the database when I need to run multiple queries. For example, i have a webpage that need to query the database to see if the user has moderator privledges, then depending on that query I have to query the DB again for moderator specific information or non-modertaor information.

So in this case how do i handle opening connections to the DB. Is it ok to generally have to open a connection to a DB multiple times on a page load?

The obvious solution is to keep the connection open. That is, open a connection, query the Db, keep the connection open, do the conditional statment ( if is_Moderator) then query the DB again for the info that I need, and then close the connection. But, from all the books that Ive been reading this is not a good practice because business logic should not been in the dataAccess layer.

Any help would be much appreciated.You should be using stored procedures to do all of this. Then this wouldn't be a problem. You could have a "wrapper" stored procedure that figures out if it's a moderator or not, then calls the appropriate stored procedure based on that information. You then wouldn't have to worry about multiple calls to the database. This is a data logic procedure. It's not "always" bad to have business logic at the database layer. It's questionable that this is even business logic.

Make sense?|||yes it did make sense.

Thankyou.

No comments:

Post a Comment