ASP正確串連資料庫

來源:互聯網
上載者:User
資料操作太頻繁了,合理的利用資料庫連接,不浪費資源,很重要!以下是我總結的資料庫連接方式!代碼多點,但比較有效! 程式碼<%
'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的一個函數,如果我們引用的目錄比較深,那麼這個函數可以確保擷取真實的資料庫路徑。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.