Data operations are too frequent. It is important to make rational use of database connections without wasting resources! The following is my summary of the database connection method! More code, but more effective! Program code <%
'Written by shaoyun site: www.devjs.com
Const adstateclosed = & h00000000
Const adstateopen = & h00000001
Dim Conn, dbpath
Dbpath = "DB \ # dB. mdb"
Sub opendb ()
On Error resume next
Getrealpath ()
Dim connstr: connstr = "provider = Microsoft. Jet. oledb.4.0; Data Source =" & dbpath
If not (isobject (conn) then set conn = server. Createobject ("ADODB. Connection ")
If conn. State = adstateopen then conn. Close ()
Conn. Open connstr
If err. Number <> 0 then
Response. Clear
Response. write "<meta http-equiv =" "Content-Type" "content =" "text/html; charset = gb2312"/> <divfont-size: 12px; font-weight: bold; Border: 1px solid #006; padding: 6px; Background: # FCC "> database connection error. Check the connection string! </Div>"
Closeconn (): Err. Clear: Response. End
End if
End sub
Sub closedb ()
If isobject (conn) then
If conn. State = adstateopen then conn. Close (): Set conn = nothing
End if
End sub
'Modify a function from zblog to obtain the real path of the database.
Function getrealpath ()
On Error resume next
Dim curpath: curpath = server. mappath ("./")&"\"
Dim FSO: Set FSO = Createobject ("scripting. FileSystemObject ")
If FSO. fileexists (curpath & dbpath) then
Realpath = curpath
Elseif FSO. fileexists (curpath & ".. \" & dbpath) then
Realpath = curpath &"..\"
Elseif FSO. fileexists (curpath & "... \ .. \" & dbpath) then
Realpath = curpath &"..\..\"
Elseif FSO. fileexists (curpath & "... \" & dbpath) then
Realpath = curpath &"..\..\..\"
Elseif FSO. fileexists (curpath & "... \" & dbpath) then
Realpath = curpath &"..\..\..\..\"
Elseif FSO. fileexists (curpath & "... \" & dbpath) then
Realpath = curpath &"..\..\..\..\..\"
End if
Dbpath = realpath & dbpath
Set FSO = nothing
Getrealpath = true: Err. Clear
End Function
Opendb ()
Closedb ()
%>
The isobject function is used to determine whether a connection object has been created. If a connection object is not created, it is created. If it is created, the state attribute is used to determine whether the connection object is enabled or disabled.
At the same time, call the on error resume next statement to capture errors to display custom error output information!
Getrealpath () is a function that I changed from zblog. If the referenced directory is deep, this function ensures that the actual database path is obtained.