Wednesday, 30 November 2011

CLOSE DATABASE CONNECTION

A common problem among hosting companies is that ASP websites do not close the database connections after they are opened. This is a basic step that you should consider to be part of mandatory code. If you do not close your database connections, many problems can occur 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. If you live in the country, a bear could walk in. If you live in the city, a mugger could walk in. Alright, well maybe leaving a database connection open won't lead to anything that bad, but it will lead to a lot of unecessary headaches for both 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.

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

All you have to do is include the "objRS.Close...objConn.Close..." code from the bottom of this example anywhere on your web page after your data is displayed. Yes, it is necessary to close both the connection and the recordset. Be careful not to include your close connection code on the page before 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.

http://www.aspwebpro.com/tutorials/asp/dbconnectionclose.asp

No comments:

Post a Comment