OleDb 查询表达式中的语法错误(缺少运算符)vb.net

Syntax error (missing operator) in query expression in OleDb vb.net

请给我一个解决方案。

我想我把查询代码搞错了

Private Sub PopulateDataGridView()
    Dim query = "select ITM,ITC,QOH,PRS FROM IFG (WHERE QOH > 0 AND ITM = @ITM OR ISNULL(@ITM, '') = '')"
    Dim constr As String = "provider=Microsoft.Jet.OLEDB.4.0; data source=C:\Users\ADMIN2\Desktop; Extended Properties=dBase IV"
    Using con As OleDbConnection = New OleDbConnection(constr)
        Using cmd As OleDbCommand = New OleDbCommand(query, con)
            cmd.Parameters.AddWithValue("@ITM", cbCountries.SelectedValue)
            Using sda As OleDbDataAdapter = New OleDbDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                dataGridView1.DataSource = dt
            End Using
        End Using
    End Using
End Sub

Syntax error in FROM clause. contents of the database

这是一个关于 SQL 语法的问题,真的,而不是 vb.net 或 oledb。

您有两个 WHERE 子句,无效 SQL。将第二个WHERE改为AND

Dim query As String = "select ITM,ITC,QOH,PRS FROM IFG WHERE QOH > 0"
query &= " AND ITM = @ITM"

顺便说一句,由于字符串在 vb.net 中是不可变的,所以您不应该构建这样的字符串(首先分配给,然后添加到),因为您显然可以避免它,因为每次连接都会创建一个新的内存中的字符串。您可以使用 &、StringBuilder 或一个长字符串。例如,利用 vb.net 语法制作多行字符串,您可以将 vb.net 更改为

Dim query = "
select ITM,ITC,QOH,PRS 
FROM IFG 
WHERE QOH > 0 
AND ITM = @ITM"

作为 SQL 查询,[主观上] 更容易阅读(当然,请根据您的逻辑添加适当的括号!)。

根据您的更新,您需要向查询添加一个参数。这是一个或多或少完整的带有一个参数的查询示例

Using con As New OleDbConnection("connection string")
    Dim query = "
        select ITM,ITC,QOH,PRS 
        FROM IFG 
        WHERE QOH > 0 
        AND ITM = @ITM"
    Using cmd As New OleDbCommand(query, con)
        cmd.Parameters.AddWithValue("@ITM", itmValue)
        Using rdr = cmd.ExecuteReader()
            For Each result In rdr.AsQueryable()
                ' do something with each result
            Next
        End Using
    End Using
End Using