随机显示数据库记录

** 随机显示数据库记录 **


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();

完整代码如下:

1@ Page Language="C#" Debug="true" 
1@Import NameSpace="System.Data.SqlClient"
1@Import NameSpace="System.Data"
 1<html>
 2<head>
 3<title>随机显示数据库记录</title>
 4</head>
 5<body>
 6<script runat="server">   
 7void Page_Load(object Sender,EventArgs E)   
 8{   
 9int RecNo=0,MaxRecNo,MinRecNo;   
10Random R = new Random();   
11SqlDataReader DR;   
12//**** 连接到数据库   
13SqlConnection CN = new SqlConnection("Server=Mengxianhui;Database=Northwind;uid=sa");   
14CN.Open();   
15//**** 找到最大的和最小的ID号   
16SqlCommand Cmd = new SqlCommand("select Max(ProductId) as MaxProdid ,Min(ProductId) as MinProdId from Products",CN);   
17DR= Cmd.ExecuteReader();   
18DR.Read();   
19MaxRecNo = (int)DR["MaxProdid"];   
20MinRecNo = (int)DR["MinProdid"];   
21DR.Close();   
22//**** 创建一个随机数   
23RecNo = R.Next(MinRecNo,MaxRecNo);   
24//**** 显示随机记录信息。   
25Cmd = new SqlCommand("select * from Products Where ProductID = " + RecNo,CN);   
26DR = Cmd.ExecuteReader();   
27DR.Read();   
28Response.Write("今日的产品名称: <b>" +DR["ProductID"] + " - " + DR["ProductName"] + "</b>");   
29DR.Close();   
30CN.Close();   
31}   
32</script>
33</body>
34</html>

Published At
Categories with Web编程
Tagged with
comments powered by Disqus