第一种方法是:
<%
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
’上面的代码是用来连接数据库的,当然一般的网页都是从外部文件引用。可以不需要重新打开。
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随机读取数据的方法:
’--- 连接数据库的代码上面已经有了
’--- ASP&Access随机读取某段数据
Randomize
’--- 得到总得记录数
dim countid
countid=conn.execute("select count(id) from product")(0)
’--- 获得随机数
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