System名称空间有一个Random类,用来产生随机数。本文就介绍利用这个Random类来随机显示数据库记录。
Random类有一个重载方法叫Next,它可以产生随机数,它允许输入两个参数,以产生这两个数之间的随机数。例如:
Random R = new Random();
Random.Next(1,100);
将会在产生1-100之间的随机数。
要随机显示数据库记录,需要知道数据库最大记录数和最小记录数。
int RecNo=0,MaxRecNo,MinRecNo;
Random R = new Random();
SqlDataReader DR;
SqlConnection CN = newSqlConnection("Server=Mengxianhui;Database=Northwind;uid=sa");
CN.Open();
SqlCommand Cmd = new SqlCommand("select Max(ProductId) as MaxProdid ,Min(ProductId) as MinProdId from Products",CN);
DR= Cmd.ExecuteReader();
DR.Read();
MaxRecNo = (int)DR["MaxProdid"] ;
MinRecNo = (int)DR["MinProdid"] ;
RecNo = R.Next(MinRecNo,MaxRecNo);
然后得到随机得到记录。
Cmd = new SqlCommand("select * from Products Where ProductID = " RecNo,CN);
DR = Cmd.ExecuteReader();
DR.Read();
Response.Write("今日的产品名称: " DR["ProductID"] " - " DR["ProductName"] "");
CN.Close();
XML/HTML代码
- <%@ Page Language="C#" Debug="true" %>
- <%@Import NameSpace="System.Data.SqlClient"%>
- <%@Import NameSpace="System.Data"%>
- <html>
- <head>
- <title>随机显示数据库记录</title>
- </head>
- <body>
- <script runat="server">
- void Page_Load(object Sender,EventArgs E)
- {
- int RecNo=0,MaxRecNo,MinRecNo;
- Random R = new Random();
- SqlDataReader DR;
- //**** 连接到数据库
- SqlConnection CN = new SqlConnection("Server=Mengxianhui;Database=Northwind;uid=sa");
- CN.Open();
- //**** 找到最大的和最小的ID号
- SqlCommand Cmd = new SqlCommand("select Max(ProductId) as MaxProdid ,Min(ProductId) as MinProdId from Products",CN);
- DR= Cmd.ExecuteReader();
- DR.Read();
- MaxRecNo = (int)DR["MaxProdid"];
- MinRecNo = (int)DR["MinProdid"];
- DR.Close();
- //**** 创建一个随机数
- RRecNo = R.Next(MinRecNo,MaxRecNo);
- //**** 显示随机记录信息。
- Cmd = new SqlCommand("select * from Products Where ProductID = " RecNo,CN);
- DR = Cmd.ExecuteReader();
- DR.Read();
- Response.Write("今日的产品名称: <b>" DR["ProductID"] " - " DR["ProductName"] "</b>");
- DR.Close();
- CN.Close();
- }
- </script>
- </body>
- </html>