2

I have a classic ASP (vbscript) web app that connect to an SQL server. On certain pages, I open multiple DB connections to pull data.

My question is:

Is it better to add a close connection function at the bottom of each page or to explicitly close the connection right after using it? Keep in mind, on these certain pages, I reopen a DB connection everytime I get data; I do not reuse the connection. IE:

Set DBread = Server.CreateObject("ADODB.Connection")
DBread.Mode = adModeRead
DBread.Open (SQL_DB_CONN)

When I close the connection, I use:

DBread.Close
Set DBread = Nothing

So, should I constantly open then close the connection OR constantly open connections, then close them once at the end of a page?

2 Answers 2

3

Keep your connections open for as short a time as possible. Connection pooling will worry about efficiency for you.

But, if you have sequential db operations, they can share the same connection. This will also allow you to use transactions.

Sign up to request clarification or add additional context in comments.

Comments

2

You should open one connection and make all queries at the top of your page then close the connection as soon as the last query has executed

Example:

Dim DBread
Set DBread = Server.CreateObject("ADODB.Connection")
DBread.Mode = adModeRead
DBread.Open (SQL_DB_CONN)

'Make SQL Calls Here and Save rows of data by using the getrows function

DBread.Close
Set DBread = Nothing

'Process rows of data here

5 Comments

Thanks, but since I am calling many external functions for queries, I try to open connections in the functions for use on other pages.
You should definitely use global functions for opening and closing the connection but it might be best if you rethought your code as opening and closing unnecessarily generates more load on your db server as well as network traffic
Maybe your functions could check to see if the connection is already open and use that instead. You could just make DBread a global variable and leave it unchanged if DBread is not nothing
@xweb if you find any answer useful mark it as a correct answer
Rafael, I will. How can I check to see if the connection is already open? I tried If DBread.State = adStateOpen but that fails if the connection is closed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.