欢迎光临
我们一直在努力

建站超值云服务器,限时71元/月

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

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 »
分享到: 更多 (0)

相关推荐

  • 暂无文章