由於使用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 = c md.ExecuteReader(System.Data.CommandBehavior.CloseConnection); GridView1.DataSource = dr; GridVIEw1.DataBind(); dr.Close(); cmd.Dispose(); cn.Dispose(); cn = null; } </script> <html XMLns="http://www.w3.org/1999/xHtml"> <head runat="server"> <title>隨機讀取Access數據庫記錄</title> </head> <body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridVIEw1" runat="server" AutoGenerateColumns="false"> <Columns> <ASP:HyperLinkField DataNavigateUrlFields="objectGuid" HeaderText="文章" DataTextFIEld="Title"
DataNavigateUrlFormatString="http://dotnet.aspx.cc/article/{0}/read.ASPx" />
</Columns>
</ASP:GridVIEw>
</div>
</form>
</body>
</Html>