Author: Meng will come from: [it] would be a wonderful world Meng Date: 2003 at 12:00:00 on April 13
The SYSTEM namespace has a Random class that generates random number. This article introduces this Random class to randomize database records. The Random class has a heavy-load method called next, which can generate random numbers, which allows two parameters to generate random numbers between the two numbers. For example: random r = new random (); random.next (1,100); will be random number between 1-100. To randomize database records, you need to know the maximum number of records and minimum records of the database. 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 ("SELECTID) AS MAXPRODID, Min (Productid) AS MinProdiDID, CN); DR = cmd.executeReader (); Dr.Read (); maxRecno = (int) DR [" MAXPRODID "]; MinRecno = (int) DR ["minprodid"]; recno = r.next (minRecno, maxRecno); then get randomly logged. CMD = New SQLCOMMAND ("Select * from products where product); DR = cmd.executeReader (); Dr.Read (); response.write (" Today's product name: " DR [" ProductID "] " - " DR [" ProductName "] " ""; cn.close (); full code as follows:
<% @ Page language = "c #" debug = "true"%>
<% @ Import namespace = "system.data.sqlclient"%>
<% @ Import namespace = "system.data"%>
hEAD>
Void Page_Load (Object Sender, Eventargs E)
{
INT Recno = 0, MaxRecno, MinRecno;
Random r = new random ();
SqlDataReader DR;
// **** Connect to the database
SqlConnection CN = New SqlConnection ("Server = mengxianhui; database = northwind; uid = sa"); cn.open ();
// **** Find the largest and smallest ID number
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 ();
// **** Create a random number
Recno = R. Next (MinRecno, MaxRecno);
// **** Display random record information.
CMD = New Sqlcommand ("SELECT * from Products Where ProductId =" Recno, CN);
DR = cmd.executeReader ();
Dr.read ();
Response.write ("Today's Product Name: " " " " " "" ProductName "] " b> ");
Dr.close ();
Cn.close ();
}
script>
body>
html>