首页 > 编程 > .NET > 正文

ASP.NET随机显示数据库记录

2024-07-10 12:55:05
字体:
来源:转载
供稿:网友
  • 本文来源于网页设计爱好者web开发社区http://www.html.org.cn收集整理,欢迎访问。
  • 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();
      
      完整代码如下:
      <%@ 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();
      //**** 创建一个随机数
      recno = 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>
    发表评论 共有条评论
    用户名: 密码:
    验证码: 匿名发表