INSERT INTO语句中的语法错误(错误3134)

时间:2018-12-30 20:40:14

标签: sql vba ms-access

我正在使用MS Access2013。我当前的问题是以下代码,我用来记录用户活动。 该表称为:tbl-activitylog并具有五列:

id
timestamps
Username
Activity
Additional

我在char之后多次检查代码,不知道出了什么问题:(

TempVars("UserName").Value = "admin"
Logging("Logon", "system")
Public Sub Logging(Activity, Additional As String)
    Dim sql_code As String
    sql_code = "INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"
    Debug.Print sql_code
    CurrentDb.Execute sql_code
End Sub

调试打印显示:

INSERT INTO tbl-activitylog(Username, Activity, Additional) VALUES('admin','Logon','System')

3 个答案:

答案 0 :(得分:1)

由于使用“-”,因此必须以这种方式进行[tbl-activitylog]

sql_code = "INSERT INTO [tbl-activitylog](Username, Activity, Additional) VALUES('" & TempVars("UserName").Value & "','" & Activity & "','" & Additional & "')"

答案 1 :(得分:0)

此3134错误表示INSERT语句中的语法错误。由于表格名称包含破折号,因此需要将其括在方括号内:

select table_b_fks, array_agg(name)
from table_a
join table_b on id = any(table_b_fks)
group by 1

通常来说,您最好也将所有字段和表名括起来,以避免与ms-access reserved words发生冲突的所有风险,例如:

INSERT INTO [tbl-activitylog]
    (Username, Activity, Additional)
    VALUES('admin','Logon','System')

答案 2 :(得分:0)

考虑参数化查询,这是在 any 数据库中运行SQL的 any 应用层语言的行业最佳实践。使用QueryDefs,您可以在MS Access中参数化查询。

甚至更多的MS Access将不允许您保存语法问题的查询。因此,请确保使用方括号或反引号转义特殊字符和保留字。

SQL (下面另存为查询对象)

PARAMETERS UsernameParam Text, ActivityParam Text, AdditionalParam Text;
INSERT INTO [tbl-activitylog] ([Username], [Activity], [Additional])
VALUES ([UsernameParam], [ActivityParam], [AdditionalParam])

VBA (上面的查询引用和绑定值,不带引号或串联)

TempVars("UserName").Value = "admin"
Logging("Logon", "system")

Public Sub Logging(Activity, Additional As String)
    Dim sql_code As String
    Dim qdef As QueryDef

    Set qdef = CurrentDb.QueryDefs("mySavedQuery")

    ' BIND PARAMS
    qdef![UsernameParam] = TempVars("UserName")
    qdef![ActivityParam] = Activity
    qdef![AdditionalParam] = Additional

    qdef.Execute dbFailOnError

    Set qdef = Nothing
End Sub