Database Connection Through VBScript Classes Part 1
Are you tired of writing the code to connect to a database over and over again?
I’ve grown very tired of it. I decided it was time to build a reusable class to hook up the connection and recordset objects I use in almost all of my projects.
The concept I came to love is a VBScript class.
Here is the code for the class.
Class DataBaseFunctions
' Declare variables to have public scope.
Public rs
Public cn
'Method to initialize connection to database
Private Sub Init
if isobject(cn) = false then
Set cn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
cn.ConnectionString = Application("DB_CONN")
cn.Open
end if
End Sub
' Method to destory objects created.
Public Sub Destroy
if isobject(rs) = true then
rs.Close
Set rs = nothing
end if
if isobject(cn) = true then
cn.Close
Set cn = nothing
end if
End Sub
End Class
Now I only need one line of code on my ASP page to initialize my database connection. Notice the use of the Application object to store the connection string. This has always been a convieniant way to store global information and make it eaiser to change later.
Add this code to your global.asa in the Application_OnStart() sub to set the Application(“DB_CONN”) variable equal to your database DSN (in this case) or a DSN-less connection string.
Application("DB_CONN") = "DSN=cvDatabase;"
Here is how you would use the DataBaseFunctions class in your ASP page :
<HTML>
<HEAD>
<!-- #INCLUDE File="class_DataBaseFunctions.asp" -->
</HEAD>
<BODY>
<%
Set db = new DataBaseFunction
db.Init
Set db.rs = db.cn.Execute("SELECT * FROM tblUser WHERE UserID = 10")
Response.Write(db.rs.Fields(1).value)
db.Destroy
Set db = Nothing
%>
</BODY>
</HTML>