Random ASP - Database Function
The following is an ASP script that I use to easily connect to a SQL database and do a query without having to retype connection strings and the like. It’s all contained in a Class that should be included in every page you have that calls for database interaction.
Class objDB
' Declare variables to have public scope
Public rs, cn
' Method to initialize the connection to the database
Private Sub Init
If isobject(cn) = false then
Set cn = Server.CreateObject("ADODB.Connection")
Set rs = Server.CreateObject("ADODB.Recordset")
cn.ConnectionString = "Provider=sqloledb; Data Source=dbpath; Initial Catalog=db; User ID=username; Password=password"
cn.Open
End If
End Sub
' Method to destroy objects that were 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
' Method to execute a SQL statement
Public Function SQL(strSQL, bResults)
If isobject(cn) = false then
Init
End If
If bResults then
rs.Open strSQL, cn, 1, 1
Else
cn.Execute(strSQL)
End If
End Function
End Class
To use this code in your ASP, create the database object and call the SQL as such:
Set fooDB = New objDB
sql = "SELECT * FROM foobar"
Call fooDB.SQL(sql,true)



47 Responses to “Random ASP - Database Function”
Please Wait
Leave a Reply