我正在尝试生成一个与我的数据库中的QuizTitle绑定的顺序唯一ID。我想从数字1开始,它将根据它是否是新的QuizTitle而增加。我不知道我的代码有什么问题,但它没有向我显示任何内容:
Private Sub QuizID()
Dim myReader As OleDb.OleDbDataReader
AConn.Open()
Dim temp As String
Try
Dim sql As String = "Select COUNT(*) as numRows FROM tblQuestions where QuizTitle = '" & frmStudReg.txtPD_UN.Text & "'"
Dim comm As OleDb.OleDbCommand = New OleDb.OleDbCommand(sql, AConn)
myReader = comm.ExecuteReader
If myReader.HasRows Then
While myReader.Read()
temp = myReader.Item("QuizID") + 1
End While
End If
myReader.Close()
Catch ex As Exception
End Try
AConn.Close()
Me.txtNewQuiz_QuizID.Text = String.Concat(temp)
End Sub
答案 0 :(得分:0)
由于您查询的所有内容都是项目数,因此请尝试使用ExecuteScalar
,如下所示:
' Assuming you've created the command already, I'm just setting the text here. You can do it via the constructor as you had done if you wish.
comm.CommandText = "SELECT COUNT(*) FROM tblQuestions WHERE QuizTitle = @QuizTitle"
comm.Parameters.Add("@QuizTitle", SqlDbType.NVarChar)
comm.Parameters("@QuizTitle").Value = frmStudReg.txtPD_UN.Text
Dim count As Integer = comm.ExecuteScalar()
此时,您可以根据需要使用count
。另请注意,我使用参数而不是字符串连接来构建查询。如果您从用户或外部源获取输入并使用它来构建查询,那么您将自己打开sql注入。