萬盛學電腦網

 萬盛學電腦網 >> 數據庫 >> sql server教程 >> 隨機得到Access數據庫記錄

隨機得到Access數據庫記錄

由於Access數據庫記錄集緩存的原因,從代碼裡得到Access數據庫隨機記錄是得不到,需要用隨機SQL語句的辦法來消除緩存。

下面就是例子:

查看例子

<%@ 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>



關鍵詞:

copyright © 萬盛學電腦網 all rights reserved