Close Database Connection

An important thing to remember is that ASP does not close database connections automatically when a script is finished running so you need to be sure to close your open connections.  If you do not close your database connections, you may run into issues like web pages hanging, slow page loads, and more.

Think of it as going through a door to your house.  Maybe the door will shut by itself, but maybe it won’t.  If it doesn’t shut, who knows what will happen.  It may lead to a lot of unnecessary headaches for you and your hosting company.

So how do I close my database connection?  It’s very simple. Here is the code from our Open Database Connections Tutorial:

<%
DIM objConn
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.ConnectionString = "DSN=myCONNECTION.dsn"
objConn.Open

DIM mySQL, objRS
mySQL = "SELECT * FROM myTABLE"
Set objRS = Server.CreateObject("ADODB.Recordset")
objRS.Open mySQL, objConn
%>

Display data from database here.

 

After your data is displayed and you are finished using your database connection, add this little piece of code to your page.

<%
objRS.Close
Set objRS = Nothing
objConn.Close
Set objConn = Nothing
%>

 

Yes, it is necessary to close both the Recordset “objRS.Close” and the Connection “objConn.Close”.  Be careful not to include your close connection code on the page above where your data is being displayed or guess what happens?  That’s right, the connection gets closed before the data can be displayed and you get lots of errors.

Well, that’s it.  Now, you know how to properly close a database connection.  Be sure to include this in your ASP coding routine and it will be smoother sailing for both you and your hosting company or server administrator.

< Back to ASP Tutorials