
|
Functions to Open a Database Connection and Record Set By Nannette Thacker - 08/16/2000 One would think this article wouldn't be necessary, but I have "inherited" code from several web sites where the previous developer has manually opened and closed database connections every time they are needed. So in this article, I am going to show you how to create a data function to call on your pages when you wish to open and close a data connection. Then all you will need is to use:
as necessary. The first step is to create your DataFunc.asp file. Well, goodness, just copy mine! In the below example, I create OpenDB() which opens the database connection using Application variables defined in the global.asa file. I automatically use "rs" throughout my projects when I create a record set from a sql string, so I go ahead and Dim it in the DataFunc.asp file.
This saves me from having to release it in my code. As you can see below, I set rs = Nothing in the CloseDB() function below.
Now, what's going on here, you might ask?
Well, if you open a database connection more than once on the same page, nothing happens. No big deal. But if you try to close it more than once and you've already closed it or never opened it, then it will generate an error. Bummer. So the above line of code checks to see if the connection has been defined and opened before it actually closes it. Hint: If you use page templates, in your pagebottom.asp page, you can always call the function to close the database connection, whether you've ever opened it or not. That way you will always have safe pages and clean code! I've included the two OpenRecordSet and CloseRecordSet functions with this, but frankly, I don't like using them and prefer working with SQL query strings. If you don't use them either, just delete them out of this function. But what if you need to have a query within a query on a page? No big deal, use the "rs" for the first one, then use rs1, rs2, or whatever for each additonal query. Just remember to set them to nothing when done:
Okay, here's how to use it: Hopefully, you will be using a page template for the top and bottom of all your pages. For details on how to do that, see Using Templates. If you are using a pagetop.asp template at the top of the page, call the include file within the pagetop.asp page, rather than each actual file. So, put the below include file in your pagetop.asp page or, if you don't use include templates on every page, call it directly on your page. Of course, use your path, not mine.
The include file has now included the function on the page. It has not yet opened the database connection. So now, when you're ready to work with your database, open it:
And, remember, use Call CloseDB() in the pagefooter.asp include page that you include at the bottom of all your pages so that you won't accidentally leave any open connections.
|
|
