我正在尝试从checkListBox中选择的选项创建一个sql查询。用户将选择他们想要的所有模块(在核对表框中)以包含来自的数据,然后它将构建查询以收集此数据。他们还将输入将包含在查询中的评级值的范围。我是使用sql的新手,所以我很难理解最终查询中缺少的运算符。
这就是我现在所拥有的:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
Dim h As Integer
Dim queryString As String
Dim moduleArray(6) As String
Dim counter As Integer = 0
Dim provider As String
Dim database As String
Dim connString As String
Dim moduleLen As Integer = 0
Dim moduleString As String = ""
Dim sqlquery As New OleDb.OleDbCommand
provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Change the following to your access database location
database = "C:\Users\mello_000\OneDrive\Google Drive\Computing\Exampapergenerator\users.accdb"
connString = provider & database
Dim myConnection As OleDbConnection = New OleDbConnection(connString)
myConnection.Open()
sqlquery.Connection = myConnection
For h = 0 To h = 6
For Each item As String In Me.CheckedListBox1.CheckedItems
moduleArray(moduleLen) = item
If moduleArray(moduleLen) = "" Then
Else
moduleLen = moduleLen + 1
End If
Next
Next
For i = 0 To moduleLen
If i = 0 Then
moduleString = "'" & moduleArray(i) & "'"
ElseIf i > 0 Then
moduleString = moduleString & "'OR'" + "'" & moduleArray(i) & "'"
End If
Next
queryString = ("SELECT QText FROM Question WHERE QModule = '" & moduleString & "' AND QRating BETWEEN '" & TextBox1.Text() & "'AND'" & TextBox2.Text())
sqlquery.CommandText = queryString
sqlquery.ExecuteNonQuery()
End Sub
但是我得到的输出是:"SELECT QText FROM Question WHERE QModule = ''C1''OR''C2'' AND QRating BETWEEN '1'AND'2"
并出现错误:
Syntax error (missing operator) in query expression 'QModule = ''C1''OR''C2'' AND QRating BETWEEN '1'AND'2'.
此外,以可打印的形式输出编号列表中所有返回数据的最佳方法是什么?
答案 0 :(得分:2)
为什么你这样做For h = 0 To h = 6
而不仅仅是For h = 0 To 6
?
"'OR'"
周围不需要单引号,只需使用" OR "
。
你的SQL语法错了。此QModule = ''C1''OR''C2''
要么必须QModule = 'C1' OR QModule = 'C2'
,要么更好QModule IN ('C1','C2')
假设QRating是数字,则不需要单引号。此QRating BETWEEN '1'AND'2'
应为QRating BETWEEN 1 AND 2.
此外,您应该考虑使用SQL参数,这样如果您的数据中有引号,则无需担心引号或转义它们。