ASP.NET 2.0下随机读取Access记录的实现方法
程序员文章站
2022-07-19 16:51:13
由于使用ado访问access数据库会有缓存,这在随机提取数据库数据时,例如:sql="select top 10 title,objectg...
由于使用ado访问access数据库会有缓存,这在随机提取数据库数据时,例如:sql="select top 10 title,objectguid from document order by rnd(id)",将得不到随机记录,下面的例子可以克服这一缺陷,实现数据库的随机读取。
c#:
复制代码 代码如下:
<%@ page language="c#" %>
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<script runat="server">
protected void page_load( object sender, eventargs e )
{
random rnd = new random(unchecked((int)datetime.now.ticks));
int intrandomnumber = rnd.next();
string connectionstring = @"provider=microsoft.jet.oledb.4.0;data source= datadirectory aspxweb.mdb;persist security info=true";
string sql = "select top 10 title,objectguid from document order by rnd(" + (-1 * intrandomnumber) + "*id)";
system.data.oledb.oledbconnection cn = new system.data.oledb.oledbconnection(connectionstring);
cn.open();
system.data.oledb.oledbcommand cmd = new system.data.oledb.oledbcommand(sql, cn);
system.data.oledb.oledbdatareader dr = cmd.executereader(system.data.commandbehavior.closeconnection);
gridview1.datasource = dr;
gridview1.databind();
dr.close();
cmd.dispose();
cn.dispose();
cn = null;
}
</script>