当前位置:编程学习 > C#/ASP.NET >>

Displaying Random Record

答案: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();

上一个:ado.net数据操作全接触一(insert,update,delete)
下一个:通过ADO.NET访问数据库

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,