如何从数据库中以随机方式检索单个记录?您提出的任何帮助将受到高度赞赏。谢谢!
这是我到目前为止所做的事情
protected void Button1_Click(object sender, EventArgs e)
{
string ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Ahmed'susopriore'\Documents\Visual Studio 2013\Projects\WebApplication11\WebApplication11\Questions.accdb";
OleDbConnection connection = new OleDbConnection(ConnectionString);
Random rnd = new Random();
rnd.Next();
string myQuery = "SELECT * FROM Questions ORDER BY rnd()";
OleDbCommand command = new OleDbCommand(myQuery, connection);
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
while (reader.Read())
{
ListBox1.Items.Add(reader["Number"]+"" );
}
}
catch (Exception ex)
{
Label1.Text = "ERROR!"+ex;
}
finally
{
connection.Close();
}
}
答案 0 :(得分:1)
如果问题的主键是questionId
更改您的代码:
string myQuery = "SELECT * FROM Questions ORDER BY rnd()";
为:
string myQuery = "SELECT Top 1 * FROM Questions ORDER BY rnd(questionID)";
或者:
string myQuery = "SELECT Top 1 * FROM Questions ORDER BY Rnd(-(100000*questionID)*Time())