如何在此代码中修复语法错误3134?

时间:2019-12-28 07:10:54

标签: sql vba ms-access

Private Sub Form_Close()

    Dim sSQL, stringSQL As String
    Dim rst As DAO.Recordset

    sSQL = "SELECT BarCode, [Goods Name] FROM tblInventory WHERE BarCode='" & Me.ID & "'"
    Set rst = CurrentDb.OpenRecordset(sSQL)
    If rst.EOF Then
        stringSQL = "INSERT INTO tblInventory(BarCode,[Goods Name],Unit,[Unit Price],[Initial Stock],[Current Stock],[Exit Item]) values('" & Me.ID & "','" & Me.GoodsName & "','" & Me.Unit & "'," & Replace(Format(Me.Price, "0.00"), ",", ".") & "," & Me.Amount & "," & Me.Amount & ",0)"
        DoCmd.SetWarnings False
        DoCmd.RunSQL [stringSQL]
        DoCmd.SetWarnings True
    Else
        stringSQL = "UPDATE tblInventory SET [Current Stock]=[Current Stock]+" & Me.Amount & " WHERE BarCode='" & Me.ID & "'"
        DoCmd.SetWarnings False
        DoCmd.RunSQL (stringSQL)
        DoCmd.SetWarnings True
    End If
    rst.Close

End Sub

2 个答案:

答案 0 :(得分:2)

首先,请注意:

Dim sSQL, stringSQL As String

导致sSQL被定义为 Variant ,而不是字符串;尽管虽然不会导致您的代码失败(因为Variant可以保存任何类型的数据),但内存效率低。

您应该使用:

Dim sSQL As String, stringSQL As String

或者,也许更具可读性:

Dim sSQL As String
Dim stringSQL As String

第二,当独立于任何其他表达式调用函数时,请勿在参数中加上任何类型的括号。

在代码中的第 11 行中,您有

DoCmd.RunSQL [stringSQL]

在第 16 行,您有

DoCmd.RunSQL (stringSQL)

这两个都应更改为:

DoCmd.RunSQL stringSQL

或者,直接提供SQL字符串,例如:

DoCmd.SetWarnings False
DoCmd.RunSQL "UPDATE tblInventory SET [Current Stock]=[Current Stock]+" & Me.Amount & " WHERE BarCode='" & Me.ID & "'"
DoCmd.SetWarnings True

此外,由于您仅使用记录集来测试记录是否存在,因此可以将其简化为DLookup调用,例如:

DLookup("BarCode","tblInventory","BarCode=Forms![YourForm]!ID")

然后使用Null测试是否返回IsNull

If IsNull(DLookup("BarCode", "tblInventory", "BarCode=Forms![YourForm]!ID")) Then
    ...
Else
    ...
End If

最后,最好使用参数化查询代替在SQL语句中串联值。

使用参数有两个主要优点:

  • 防止SQL注入。
  • 自动处理SQL数据类型。

例如,考虑以下代码:

Private Sub Form_Close()
    If IsNull(DLookup("BarCode", "tblInventory", "BarCode=Forms![YourForm]!ID")) Then
        With CurrentDb.CreateQueryDef _
            ( _
                "", _
                "insert into tblInventory(BarCode,[Goods Name],Unit,[Unit Price],[Initial Stock],[Current Stock],[Exit Item]) " & _
                "values(@id, @goodsname, @unit, @unitprice, @initstock, @stock, 0)" _
            )
            .Parameters(0) = Me.ID
            .Parameters(1) = Me.GoodsName
            .Parameters(2) = Me.Unit
            .Parameters(3) = Replace(Format(Me.Price, "0.00"), ",", ".")
            .Parameters(4) = Me.Amount
            .Parameters(5) = Me.Amount
            .Execute
        End With
    Else
        With CurrentDb.CreateQueryDef _
            ( _
                "", _
                "update tblInventory set [Current Stock]=[Current Stock]+@amount where BarCode=@id" _
            )
            .Parameters(0) = Me.Amount
            .Parameters(1) = Me.ID
            .Execute
        End With
    End If
End Sub

答案 1 :(得分:0)

尝试手动运行带有某些值的SQL。

您可能需要使用参数或正确连接变量,例如使用我的函数CSql