首页 > 开发 > 综合 > 正文

Displaying Random Record

2024-07-21 02:22:30
字体:
来源:转载
供稿:网友
system namespace has a random class which is used for generating random numbers. this article explains how to display a random record from a database table using the random class.

the random class has an overloaded method named next which will generate random numbers. one variant of this next method takes in the minimum and maximum numbers and generates random number within the range. for example:

random r = new random();
random.next(1,100);


will generate a random number between 1 and 100.

to display a random record from the database we will pass the maximum value for the id column and minimum value for the id column to the next method and generate a random number.

int recno=0,maxrecno,minrecno;
random r =  new random();
sqldatareader dr;
sqlconnection cn = new sqlconnection("server=yourservername;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);


then we will fetch the the record whose id is equal to the random number generated.

cmd = new sqlcommand("select * from products where productid = " + recno,cn);
dr = cmd.executereader();
dr.read();
response.write("product of the day <b>" + dr["productname"] + "</b>");
cn.close();

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表