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

标签 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\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()";

到:

string myQuery = "SELECT Top 1 * FROM Questions ORDER BY rnd(questionID)";

或者:

string myQuery = "SELECT Top 1 * FROM Questions ORDER BY Rnd(-(100000*questionID)*Time())

关于c# - 从数据库中获取单个随机值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20302064/

相关文章:

sql - access sql 查询中的 YES/NO 字段类型是什么?

c# - 具有弯曲斜边的多边形三角形

ms-access - 如何搜索 VBA 代码文件

c# - 如何检查类成员是否不为 null 或为空

asp.net - Visual Studio 中 Web API 和 Azure API APP 的区别

c# - 为什么没有触发 catch block ?

c# - ASP.NET 配置页面

python - 使用 pyodbc 连接 mdb 表

c# - 这是什么日期和时间格式?

c# - 使用 ASPNETCORE_ENVIRONMENT 覆盖 Azure 上的 appsettings.json