对于Asp开发中对数据库的连接管理,目前一般的处理方法都是调用一个conn.asp页面,在里面定义好相关的变量,然后根据不同的数据库类型,建立好对应的Connection;以后其他需要数据库联接的地方就调用该页面,然后进行相应处理!
我在最近的研究中发现,其实这种方法并不是最优化的,对于稍大型一下的系统论坛来说,在每个页面调用时候如果超过连接时间,就需要重新建立一遍对于数据库的连接;我的初步想法是:在conn.asp页面里面,将一个打开的Connection赋给Application保存,然后,对于每个新连接用户,再将该Application的连接赋给Session;这样就可以保证每一个用户的只建立一个Connection,对于速度提升和数据库负载会有一定的帮助尤其是用户多的时候。(最近因为要做一个信息平台,才接触Asp开发,难免说错,请见谅!)
附上我的conn.asp代码:
<%
xzcInforCookies = "xzcInfor"
on error resume next
If g_dataBaseSort = "A" Then
g_connStr = "DBQ="& server.MapPath (""&g_dataPath&"\"&g_DBMasterName&"") &";DRIVER={Microsoft Access Driver (*.mdb)};"
SqlNowString = "Now()"
SqlChar = "'"
connstr="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath(""&g_dataPath&"\"&g_DBMasterName&"")
Else
SqlLocalName ="192.1.*.*" '连接IP
SqlUsername ="****" '用户名
SqlPassword ="****" '用户密码
SqlDatabaseName="***" '数据库名
g_connStr = "Provider=Sqloledb; User ID=" & SqlUsername & "; Password=" & SqlPassword & "; Initial Catalog = " & SqlDatabaseName & "; Data Source=" & SqlLocalName & ";"
SqlNowString = "GetDate()"
SqlChar = ""
ver = "4.10 SQL"
End If
'========================================================
'-- use Application 's connection for better performance
'--------------------------------------------------------
if isObject(Application(xzcInforCookies & "conn")) = False then
set g_conn = server.CreateObject("adodb.connection")
g_conn.CommandTimeout = 60 '以秒为单位
g_conn.Open g_connStr
if g_conn.Errors.count>0 then '错误处理(包括连接错误和oracle数据库错误)
for i=0 to g_conn.Errors.count-1
tempErr=replace(replace(replace(g_conn.Errors(i).Description,vbcrlf,""),vbcr,""),vblf,"")
Response.Write "<script language='vbscript'>" + vbcrlf
Response.write "MsgBox ""发生数据库连接错误,请于管理员联系。错误提示如下:""&vbcrlf&vbcrlf&"""&tempErr&""",vbOKonly,""错误提示信息""" + vbcrlf
Response.Write "</script>"
next
Response.End
end if
Application.Lock
set Application(xzcInforCookies & "conn") = g_conn
Application.UnLock
end if
'=========================================
'-- every user use own session connection
'-----------------------------------------
if session(session.sessionid & "conn") = "" then
set session(session.sessionid & "conn") = Application(xzcInforCookies & "conn")
end if
set g_conn = session(session.sessionid & "conn")
%>