您的位置:首页 > 数据库

随机显示数据库一条记录

2007-10-10 12:33 330 查看

protected void Page_Load(object sender, EventArgs e)




...{


dataBind();


}


public void dataBind()




...{


int RecNo = 0, RecNo2 = 0, MaxRecNo, MinRecNo;


Random R = new Random();


SqlDataReader DR;


//**** 连接到数据库


SqlConnection CN = new SqlConnection("Server=.;Database=Northwind;uid=sa;pwd=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);


RecNo2 = 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>");


//this.Label1.Text = DR["ProductID"].ToString() ;


//this.Label2.Text = DR["ProductName"].ToString();


DR.Close();


CN.Close();


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: