语法错误:查询中的逗号表达访问SQL语句

时间:2016-03-08 18:09:07

标签: mysql vb.net ms-access

我非常需要你的帮助。我有以下代码,它根据用户的输入返回数据网格视图中显示的ms访问表。但是当我尝试运行它时,我遇到了错误"查询表达式中的语法错误(逗号)' lastname ='' ,firstname ='' ,midname ='''。"。请有人帮帮我

这是我的代码。

  Dim sql As String = "SELECT `lastname` as 'FAMILY NAME',`firstname` as 'NAME', `midname` AS 'MIDDLE NAME', `sex` as 'SEX', `birthdate` as 'BIRTHDAY', `Address` as 'ADDRESS', `barangay` AS 'BARANGAY', `patientID` AS 'PID' FROM `tblinformation_offline` WHERE lastname = '" & TextBox1.Text & "' , firstname = '" & TextBox3.Text & "' , midname = '" & TextBox4.Text & "' "
        Dim cn As New OleDbConnection(constring)
        cn.Open()
        Dim da As New OleDbDataAdapter(sql, cn)
        Dim ds As New DataSet
        da.Fill(ds, "AccessData")
        cn.Close()
        With Me.DataGridView1
            .DataSource = ds
            .DataMember = "AccessData"
        End With
        ds = Nothing
        da.Dispose()
        cn = Nothing

1 个答案:

答案 0 :(得分:1)

第一个问题,WHERE子句是由AND或OR等逻辑运算符链接在一起的一个或多个条件。您的WHERE列出了一系列值,这不是有效的语法

.... FROM `tblinformation_offline` 
     WHERE lastname =  'xxxxx' 
     AND firstname = 'yyyyyy' 
     AND midname = 'zzzzz" 

这将解决您的即时错误 正如您所看到的,我已经删除了字符串连接,以便您更清楚地看到错误,但现在存在使用字符串连接来构建SQL查询的问题。不要这样做但是使用参数化查询

在参数化查询中,您使用MySqlCommand的Parameters集合来传递您的值,而包含该文本的字符串则填充参数的占位符

 Dim sql As String = "SELECT ...... FROM `tblinformation_offline` " & _
      "WHERE lastname = @lname AND firstname = @fname AND midname = @mname" 
 Using cn As New OleDbConnection(constring)
 Using da As New OleDbDataAdapter(sql, cn)
    da.SelectCommand.Parameters.Add("@lname", MySqlDbType.VarChar).Value = TextBox1.Text
    da.SelectCommand.Parameters.Add("@fname", MySqlDbType.VarChar).Value = TextBox3.Text
    da.SelectCommand.Parameters.Add("@mname", MySqlDbType.VarChar).Value = TextBox4.Text
    Dim ds As New DataSet
    da.Fill(ds, "AccessData")
    cn.Close()
    With Me.DataGridView1
        .DataSource = ds
        .DataMember = "AccessData"
    End With
    ds = Nothing
End Using
End Using

最后在使用的查询文本中有错误。当你写

"SELECT `lastname` as 'FAMILY NAME' ....

您正在创建记录,其中列姓氏的值用字符串" FAMILY NAME"填充。因为你在列周围使用单引号字符而不是反引号(同样适用于其他列)