【问题标题】:Getting a single random value from a database从数据库中获取单个随机值
【发布时间】:2013-11-30 15:38:38
【问题描述】:

如何以随机方式从数据库中检索单个记录?您提出的任何帮助将不胜感激。谢谢!

这就是我到目前为止所做的

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

【问题讨论】:

  • 您现有的代码有什么问题?你得到一个错误,还是没有给出预期的结果?它在做什么你不希望它做?
  • 我现在拥有的现有代码显示列中的所有项目并以相反的顺序执行而不是随机执行
  • 仅仅因为它以您识别的顺序返回并不意味着它不是随机的。如果不指定 order by 子句,则无法保证来自 sql 数据库的顺序。
  • 没有错误。我的目标是从数据库中获取单个随机项,而不是整个列。

标签: c# asp.net ms-access


【解决方案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())

【讨论】:

  • 快到了...它以相反的顺序而不是随机顺序执行并显示该列中的所有项目
  • 我没有关注你。 “display all items in that column”是什么意思
  • iv 在我的数据库中有一个名为“数字”的列,它从 1 到 4。使用 while 循环,我将数字添加到 ListBox1.Items.Add(reader["Number"]+"" );一旦我运行程序并单击按钮,它们就会显示为 4321
  • 它说 ERROR!System.Data.OleDb.OleDbException (0x80040E14): Undefined function 'NEWID' in expression。我如何定义“NEWID”?
  • 对不起,我以为你使用的是 Sql server。我更改了使用 Ms Access 数据库的代码。
猜你喜欢
  • 2017-07-06
  • 1970-01-01
  • 1970-01-01
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-07
  • 2020-06-10
  • 2014-06-01
相关资源
最近更新 更多