从 VB.NET 复选框选项构建 SQL 查询时遇到问题
Posted
技术标签:
【中文标题】从 VB.NET 复选框选项构建 SQL 查询时遇到问题【英文标题】:Trouble building an SQL Query from VB.NET checklistbox options 【发布时间】:2016-05-08 03:51:34 【问题描述】:我正在尝试从 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'.
此外,以可打印的形式在编号列表中输出所有返回数据的最佳方式是什么?
【问题讨论】:
【参考方案1】:您为什么要这样做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 参数,这样如果您的数据中有引号,您就不必担心引号或转义它们。
【讨论】:
以上是关于从 VB.NET 复选框选项构建 SQL 查询时遇到问题的主要内容,如果未能解决你的问题,请参考以下文章