第一種方法是:
<%
Dim Db,Conn
Db = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Server.MapPath("date/shop.mdb")
Set Conn = Server.CreateObject("ADODB.Connection")
Conn.open Db
’上面的(de)代碼是用(yòng)來(lái)連接數據庫的(de),當然一般的(de)網頁都是從外部文件引用(yòng)。可(kě)以不需要重新打開。
Randomize(Timer())
SQL = "SELECT top 18 * FROM snews WHERE iclass=10 ORDER BY Rnd(-(ID + " & Int((10000 * Rnd) + 1) & "))"
Set RS = Server.CreateObject("ADODB.RecordSet")
RS.Open SQL,Conn,1,1
If Not RS.EOF Then
RS.MoveFirst
For I = 1 To RS.RecordCount
%>
Response.Write rs("title")&"
"
<%
RS.MoveNext
Next
End If
RS.Close
Set RS = Nothing
%>
方法二:
set rsn=server.createobject("adodb.recordset")
randomize
sql="select top 20 * from news order by rnd(-id-" & rnd & ")"
rsn.open sql,conn,1,1
介紹另外一種ASP随機讀取數據的(de)方法:
’--- 連接數據庫的(de)代碼上面已經有了(le)
’--- ASP&Access随機讀取某段數據
Randomize
’--- 得(de)到總得(de)記錄數
dim countid
countid=conn.execute("select count(id) from product")(0)
’--- 獲得(de)随機數
dim rndid
rndid=int(rnd*countid)
rndid=rndid+5
dim rs,sql
’--- SQL查詢
sql="select top 5 id,name from product where id in (select top "&rndid&" id from product) order by id desc"
’Response.Write(sql)
set rs=conn.execute(sql)
if not rs.eof then
do while not rs.eof
response.Write(rs(0)&" - "&rs(1)&"
")
rs.movenext
loop
end if
set rs=nothing