站点信息 访问统计:69056     在线人数:12    本次启动时间:2009-1-7 4:39:49
当前位置:  Csdtn 首页->数据库->SQL->文章
注册阿里妈妈赚广告费
Google
随机显示数据库记录
作者:中国C#技术学习中心 时间:2007-10-15  点击:424  本文Tag:MySql | MsSql | 数据库 | c#.net

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