现在的位置: 首页 > 综合 > 正文

ASP正确连接数据库

2012年12月10日 ⁄ 综合 ⁄ 共 1845字 ⁄ 字号 评论关闭
数据操作太频繁了,合理的利用数据库连接,不浪费资源,很重要!以下是我总结的数据库连接方式!代码多点,但比较有效!
程序代码 程序代码
<%
'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的一个函数,如果我们引用的目录比较深,那么这个函数可以确保获取真实的数据库路径。

抱歉!评论已关闭.