|
|
| D: | Domains | Authors.aspalliance.com | Stevesmith | Articles | Data Connection Procedures |
|
Data Connection Procedures This sample application was written by Kevin Dill, a co-worker of mine, and presents a very elegent way of connecting to a database using a few simple VBScript procedures. I've modified it somewhat to fit my needs, but the basics of it are still his. The first procedure creates a connection to the database.
'-------------------------------------
' This procedure opens the generic
' database connection as necessary.
'-------------------------------------
sub DBConnect
if isempty(DataConn) then
set DataConn = Server.CreateObject("ADODB.Connection")
DataConn.ConnectionTimeout = Session("myconnection_ConnectionTimeout")
DataConn.CommandTimeout = Session("myconnection_CommandTimeout")
DataConn.Open Session("aspdb_ConnectionString"), Session("myconnection_RuntimeUserName"), Session("myconnection_RuntimePassword")
if Session("Debug")>0 then response.write(chr(34) & "" & chr(34))
end if
end sub
Then, the actual query code is as follows:
'-----------------------------------------------------------
' This function executes a sql query against a database,
' creating a new database connection as necessary.
' It returns a recordset object as a result of the query.
'-----------------------------------------------------------
function DBQuery(sql)
DBConnect
if Session("Debug")>0 then Response.Write(chr(34) & "" & chr(34))
set DBQuery = DataConn.execute(sql)
end function
To use these two routines, simply call DBQuery with your sql statement, as follows: 'Pull all records from employee into recordset rs sql = "SELECT * FROM Employee" set rs = DBQuery(sql) That's it. Note that this doesn't give you the control that the ADO methods give you, such as specifying lock and cursor type, but for most applications and for most beginners, these are not necessary; the default values work just fine. Also note that the debug code is generated if the session debug level is set. To view an example of this program, click here. Source code of the link listed above: 1 <% OPTION EXPLICIT %>2 <!-- #INCLUDE VIRTUAL="/stevesmith/include/articleformat.asp" --> 3 <!-- #INCLUDE VIRTUAL="stevesmith/top.asp"--> 4 <% 5 ' top.asp has my procedures in it. Put your frequently used functions in an include 6 ' file like this for ease of portability and maintenance. 7 8 Dim sql 9 Dim rs 10 11 'Set Article Title 12 Call ArticleHeader("DBQuery Example","","") 13 14 sql = "SELECT DISTINCT(ip) FROM currentuser" 15 set rs = DBQuery(sql) 16 %> 17 <UL>IP Addresses currently connected to StevenatorASP 18 <% 19 While Not RS.EOF 20 %> 21 <LI><%=rs("ip")%> 22 <% 23 rs.MoveNext 24 Wend 25 %> 26 </UL> 27 28 <% 29 Call ArticleFooter() 30 %> |
|
|
|
|
|
|
|