由於使用ADO訪問Access數據庫會有緩存,這在隨機提取數據庫數據時,例如:sql="selecttop10Title,objectGuidfromDocumentOrderByRnd(id)",將得不到隨機記錄,下面的例子可以克服這一缺陷,實現數據庫的隨機讀取。
C#:
<@PageLanguage="C#">
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xHtml1-transitional.dtd">
<scriptrunat="server">
protectedvoidPage_Load(objectsender,EventArgse)
...{
Randomrnd=newRandom(unchecked((int)DateTime.Now.Ticks));
intintRandomNumber=rnd.Next();
stringConnectionString=@"Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|ASPxWeb.mdb;PersistSecurityInfo=True";
stringsql="selecttop10Title,objectGuidfromDocumentOrderByRnd(" (-1*intRandomNumber) "*id)";
System.Data.OleDb.OleDbConnectioncn=newSystem.Data.OleDb.OleDbConnection(ConnectionString);
cn.Open();
System.Data.OleDb.OleDbCommandcmd=newSystem.Data.OleDb.OleDbCommand(sql,cn);
System.Data.OleDb.OleDbDataReaderdr=cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection);GridView1.DataSource=dr;GridVIEw1.DataBind();dr.Close();cmd.Dispose();cn.Dispose();cn=null;}</script><htmlXMLns="http://www.w3.org/1999/xHtml"><headrunat="server"><title>隨機讀取Access數據庫記錄</title></head><body><formrunat="server"><div><ASP:GridVIEwrunat="server"AutoGenerateColumns="false"><Columns><ASP:HyperLinkFieldDataNavigateUrlFields="objectGuid"HeaderText="文章"DataTextFIEld="Title"
DataNavigateUrlFormatString="http://dotnet.ASPx.cc/article/{0}/read.ASPx"/>
</Columns>
</ASP:GridVIEw>
</div>
</form>
</body>
</Html>