tions GetRows(),GetString() 或者 Save() (ADO 2.5)都非常得快速而且简单,这里有个函数,描述了如何使用GetRows()返回记录集数据的数组:
'' Get Recordset, return as an Array
Function FetchEmploymentStatusList
Dim rs
Set rs = CreateObject("ADODB.Recordset")
rs.Open "select StatusName, StatusID from EmployeeStatus", _
"dsn=employees;uid=sa;pwd=;"
FetchEmploymentStatusList = rs.GetRows() " Return data as an Array
rs.Close
Set rs = Nothing
End Function
上述代码的一个更深的技巧是为列表缓存了HTML。下面是个简单的例子:
'' Get Recordset, return as HTML Option list
Function FetchEmploymentStatusList
Dim rs, fldName, s
Set rs = CreateObject("ADODB.Recordset")
rs.Open "select StatusName, StatusID from EmployeeStatus", _
"dsn=employees;uid=sa;pwd=;"
s = "<select name=""EmploymentStatus">" & vbCrLf
Set fldName = rs.Fields("StatusName") '' ADO Field Binding
Do Until rs.EOF
'' Next line violates Don''t Do String Concats,
'' but it''s OK because we are building a cache
s = s & " <option>" & fldName & "</option>" & vbCrLf
rs.MoveNext
Loop
s = s & "</select>" & vbCrLf
rs.Close
Set rs = Nothing '' See Release Early
FetchEmploymentStatusList = s '' Return data as a String
End Function
在合适的环境下,可以在Application或者Session中缓存ADO记录集本身,但是有2点提示:
ADO必须是自由线程标记的
需要使用disconnected recordset方式
如果不能保证上述2个条件,就不要缓存ADO记录集,因为这会产生很大的危险性。
当在Application或Session中保存数据后,数据将一直保持,除非程序改变它、Session变量到期或者Web应用程序重新启动。如果数据需要更新,怎么办?可以调用只有管理员才能访问的ASP页面来更新数据,或者,通过函数周期性的自动更新数据。下面的例子中,与缓存数据一起保存了时钟标记,过一段时间后,就刷新数据。
<%
'' error handing not shown
Const UPDATE_INTERVAL = 300 '' Refresh interval, in seconds
'' Function to return the employment status list
Function GetEmploymentStatusList
UpdateEmploymentStatus
GetEmploymentStatusList = Application("EmploymentStatusList")
End Function
'' Periodically update the cached data
Sub UpdateEmploymentStatusList
Dim d, strLastUpdate
strLastUpdate = Application("LastUpdate")
If (strLastUpdate = "") Or _
(UPDATE_INTERVAL < DateDiff("s", strLastUpdate, Now)) Then
'' Note: two or more calls might get in here. This is okay and will simply
'' result in a few unnecessary fetches (there is a workaround for this)
'' FetchEmploymentStatusList function (not shown)
'' fetches data from DB, returns an Array
d = FetchEmploymentStatusList()
'' Update the Application object. Use Application.Lock()
'' to ensure consistent data
Application.Lock
Application("EmploymentStatusList") = d
Application("LastUpdate") = CStr(Now)
Application.U