选择具有最低值的随机数据库记录

时间:2015-12-26 06:26:49

标签: mysql vb.net visual-studio-2013

对于VB来说是非常新的,如果我没有多大意义那么道歉。 我有一个有三个领域的琐事问题数据库:问题,答案和时间问题。 我希望能够点击一个按钮并从具有最低Times Asked值的记录中随机接收数据库中的问题,然后在该记录的Times Asked值中添加一个。 谁能帮我吗?这是我到目前为止所得到的:

Private DBCon As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; "Data Source=Trivia.accdb;")

Public Sub GenerateQuestion()

DBCon.Open()

'grab how many questions there are total
    Dim QuestionsQuery As String = "SELECT COUNT(*) FROM Questions"
    Dim QuestionsCmd As New OleDbCommand(QuestionsQuery, DBCon)
    Dim NumOfQuestions As Integer = QuestionsCmd.ExecuteScalar()

    'grab the lowest number from Times Asked
    Dim SeenQuery As String = "SELECT MIN(`Times`) FROM Questions"
    Dim SeenCmd As New OleDbCommand(SeenQuery, DBCon)
    Dim SeenReader As OleDb.OleDbDataReader = SeenCmd.ExecuteReader
    SeenReader.Close()

 End Sub

从另一个窗体上的按钮调用此子窗口,当我单击该按钮时,我得到一个例外,因为行/列中没有数据。即使我设法得到这个值,但我不知道下一步是什么,实际从最小的Times值中抓取一个随机问题,并为该问题的Times值添加一个。

这里是我正在使用atm的表: http://i.imgur.com/2vwlVQR.jpg

编辑:对于将来发现这一点的人来说,修复问题的代码是:

Imports System.Data.OleDb
   Dim rng As New Random
Dim connection As OleDb.OleDbConnection

Private Function GetQuestionWithAnswer() As Tuple(Of String, String)
    'Use XML literals for the SQL statements.
    Dim selectSql = <sql>
                    SELECT *
                    FROM Questions
                    WHERE Times =
                    (
                        SELECT MIN(Times)
                        FROM Questions
                    )
                </sql>
    Dim updateSql = <sql>
                    UPDATE Questions
                    SET Times = @Times
                    WHERE ID = @ID
                </sql>

    Using connection As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=Trivia.accdb;")
        Dim adapter As New OleDbDataAdapter(selectSql.Value, connection)
        Dim updateCommand = New OleDbCommand(updateSql.Value, connection)

        With updateCommand.Parameters
            .Add("@Times", OleDbType.Integer, 0, "Times")
            .Add("@ID", OleDbType.Integer, 0, "ID")
        End With

        adapter.UpdateCommand = updateCommand

        Dim table As New DataTable

        'Getall the questions that have been asked the fewest number of times.
        adapter.Fill(table)

        'Select a question at random.
        Dim record = table.Rows(rng.Next(table.Rows.Count))

        'Increment the number of times the question has been asked and save the change.
        record("Times") = CInt(record("Times")) + 1
        adapter.Update(table)

        'Package up the selected question.
        LblQuestion.Text = record(1)
        Return Tuple.Create(CStr(record("Question")), CStr(record("Answer")))

    End Using
End Function

0 个答案:

没有答案