ASP

ASP CLASS / DBConn

mulderu 2008. 4. 12. 11:14

Copy From : http://www.developersdex.com/gurus/articles/497.asp

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

'Method to execute a SQL statment against database connection.

Public Function SQL(strSQL,bResults)
   Init  
  if bResults then  
   Set rs = cn.Execute(strSQL)  
   rs.MoveFirst  
  else
   cn.Execute(strSQL)
  end if    
End Function

 
End Class
%>
---------------------------------------------------------------------------------
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>