Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 从数据库中获取单个随机值_C#_Asp.net_Ms Access - Fatal编程技术网

C# 从数据库中获取单个随机值

C# 从数据库中获取单个随机值,c#,asp.net,ms-access,C#,Asp.net,Ms Access,如何从数据库中以随机方式检索单个记录?我们将非常感谢您提出的任何帮助。谢谢 这就是我到目前为止所做的 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\Projec

如何从数据库中以随机方式检索单个记录?我们将非常感谢您提出的任何帮助。谢谢

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

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

如果问题的主键是
questionId
将代码更改为:

string myQuery = "SELECT * FROM Questions ORDER BY rnd()";
致:

或:


您现有的代码有什么问题?您是否得到了错误,还是没有给出预期的结果?你不希望它做什么?我现在拥有的现有代码显示了列中的所有项目,并以相反的顺序执行,而不是随机执行,只是因为它以你识别的顺序返回并不意味着它不是随机的。如果不指定ORDERBY子句,则无法保证来自sql数据库的顺序。没有错误。我的目标是从数据库中获取一个随机项,而不是整个列。几乎就在那里…它以相反的顺序执行,而不是随机项,并显示该列中的所有项。我没有跟踪您。你的意思是“
显示该列中的所有项目”
“我的数据库中有一个名为“Number”的列,它从1到4。使用while循环,我将数字添加到ListBox1.Items.Add(reader[“Number”]+);一旦我运行程序并点击按钮,它们就会显示为4321,表示错误!System.Data.OleDb.OLEDBEException(0x80040E14):表达式中未定义函数“NEWID”。如何定义“NEWID”?抱歉,我以为您使用的是Sql server。我更改了使用Ms Access数据库的代码。
string myQuery = "SELECT Top 1 * FROM Questions ORDER BY rnd(questionID)";
string myQuery = "SELECT Top 1 * FROM Questions ORDER BY Rnd(-(100000*questionID)*Time())