資料操作太頻繁了,合理的利用資料庫連接,不浪費資源,很重要!以下是我總結的資料庫連接方式!代碼多點,但比較有效! 程式碼<%
'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"">資料庫連接出錯,請檢查串連字串!</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
'修改自ZBlog的一個函數,用來擷取資料庫的真實路徑
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()
%>
isobject函數用來判斷連線物件是否已經建立,沒有建立就建立,建立了就用state屬性判斷它的狀態是開啟還是關閉
同時調用On Error Resume Next語句捕獲錯誤,以顯示我們自訂的錯誤輸出資訊!
GetRealPath()是我改自Zblog的一個函數,如果我們引用的目錄比較深,那麼這個函數可以確保擷取真實的資料庫路徑。