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