數(shù)據(jù)庫(kù)連接是一種關(guān)鍵的有限的昂貴的資源,這一點(diǎn)在多用戶的網(wǎng)頁(yè)應(yīng)用程序中體現(xiàn)得尤為突出。對(duì)數(shù)據(jù)庫(kù)連接的管理能顯著影響到整個(gè)應(yīng)用程序的伸縮性和健壯性,影響到程序的性能指標(biāo)。數(shù)據(jù)庫(kù)連接池正是針對(duì)這個(gè)問(wèn)題提出來(lái)的。數(shù)據(jù)庫(kù)連接池負(fù)責(zé)分配、管理和釋放數(shù)據(jù)庫(kù)連接,它允許應(yīng)用程序重復(fù)使用一個(gè)現(xiàn)有的數(shù)據(jù)庫(kù)連接,而再不是重新建立一個(gè);釋放空閑時(shí)間超過(guò)最大空閑時(shí)間的數(shù)據(jù)庫(kù)連接來(lái)避免因?yàn)闆](méi)有釋放數(shù)據(jù)庫(kù)連接而引起的數(shù)據(jù)庫(kù)連接遺漏。這項(xiàng)技術(shù)能明顯提高對(duì)數(shù)據(jù)庫(kù)操作的性能。
但是這項(xiàng)技術(shù)一般在java ,php ,.net 里面運(yùn)用到,asp很少用到,因?yàn)橐恍┢髽I(yè)網(wǎng)站根本就不需要這樣的技術(shù)。
也不是不能使用,下面就是研究出來(lái)的asp版本,能夠加快網(wǎng)頁(yè)的訪問(wèn)速度,降低數(shù)據(jù)庫(kù)的壓力。
1.數(shù)據(jù)庫(kù)連接文件 DbPool.asp
< % Const PoolSize = 10 Const Connstr = "Driver={SQL Server};Server=(local);UID=sa;word=555;Database=db" Function GetRandString(lenth) Dim rndstr,i Randomize rndstr = "" i = 1 do while i <= lenth rndstr = rndstr & Chr(cint(((120 - 98 + 1) * Rnd )+ 97)) i = i + 1 loop GetRandString = rndstr End Function Function CreateDbConn() Dim DbConn,ConnKey Set DbConn = Server.CreateObject("ADODB.Connection") DbConn.Open Connstr ConnKey = GetRandString(10) DbPool.Add ConnKey,DbConn End Function Function GetDbConn() Dim CurKey,Keys If DbPool.Count > 0 Then Keys = DbPool.Keys ' 獲取鍵名。 CurKey = Keys(0) Response.Write "Cur DbConn Key Is : " & CurKey & "<br />" Set Conn = Server.CreateObject("ADODB.Connection") Set Conn = DbPool(CurKey) If Conn.State = adStateClosed Then '如果這個(gè)連接已經(jīng)關(guān)閉,將其從池里注銷,再新建一個(gè)可用的連接并添加到池里 DbPool.Remove CurKey Call CreateDbConn() '新建一個(gè)連接并添加到池里 Set GetDbConn = GetDbConn() Else '否則的話,將其從池里注銷,然后將復(fù)制的對(duì)象返回 DbPool.Remove CurKey Set GetDbConn = Conn Exit Function End If Else Response.Write "連接池已用完,請(qǐng)重新初始化應(yīng)用程序" Response.End End if End Function Function FreeDbConn(DbConn) DbPool.Add GetRandString(10),DbConn End Function
2.全局文件 global.asa
<object ID="DbPool" Progid="Scripting.Dictionary" Scope="Application" runat="server"></object> <!--#include file="DbPool.asp"--> < % Sub Application_OnStart Dim ConnKey For i = 1 To PoolSize '建立指定數(shù)目的數(shù)據(jù)庫(kù)連接 CreateDbConn() Next End Sub Sub Application_OnEnd DbPool.RemoveAll End Sub %>
3.測(cè)試文件 test.asp
<!--#include file="DbPool.asp"--> < % Response.Write "Test Start:<br>" Response.Write "Current Objects count : " & DbPool.Count & "<br />" Set dbconn = Server.CreateObject("ADODB.Connection") Set dbconn = GetDbConn() Response.Write "get one connection from pool <br />" Response.Write "Current Objects count : " & DbPool.Count & "<br />" Set Rs = Server.CreateObject("ADODB.Recordset") Rs.open "select * from mkdb",dbconn,1,1 Do While Not rs.eof Response.write Rs("v_oid") & "<br />" Rs.movenext loop FreeDbConn(dbconn) Response.Write "free one connection to pool <br />" Response.Write "Current Objects count : " & DbPool.Count & "<br />" %>