由于access数据库记录集缓存的原因,从代码里得到access数据库随机记录是得不到,需要用随机sql语句的办法来消除缓存。
下面就是例子:
查看例子http://dotnet.aspx.cc/exam/getrandom.aspx
<%@ page language=”c#” debug=”true” %>
<%@ import namespace=”system.data” %>
<%@ import namespace=”system.data.oledb” %>
<title>随机得到access数据库记录</title>
<script runat=”server”>
void page_load(object src,eventargs e)
{
if(!ispostback)
{
string myconnstring = “provider=microsoft.jet.oledb.4.0;data source=”
+ server.mappath(“aspxweb.mdb.ascx”);
random r = new random();
int intrandomnumber = r.next(1,1000);
string sql = “select top 10 id as 序号,title as 标题 from document order by rnd(“
+ (-1 * intrandomnumber).tostring() + “*id)”;
oledbconnection myconnection = new oledbconnection(myconnstring);
myconnection.open();
oledbcommand cmd = new oledbcommand(sql,myconnection);
oledbdatareader dr = cmd.executereader();
datagrid1.datasource = dr;
datagrid1.databind();
cmd.dispose();
myconnection.close();
myconnection.dispose();
myconnection = null;
}
}
</script>
<form runat=server>
<asp:datagrid id=”datagrid1″ horizontalalign=”center”
width=”600px” runat=”server” font-size=”9pt”>
<alternatingitemstyle backcolor=”#eeeeee”></alternatingitemstyle>
<headerstyle backcolor=”#aaaadd” font-bold=”true” horizontalalign=”center” />
</asp:datagrid>
</form>