vba代码在UPDATE语句中生成语法错误

时间:2019-07-03 16:32:47

标签: access-vba

单击按钮后,我得到以下代码,它在UPDATE语句中生成3144语法错误。我似乎找不到导致错误的因素。

strUpdate = "Update VehicleInfo SET " & _
"Vic1License ='" & strPlate1 & "', Vic1Make ='" & strMake1 & "', Vic1Model ='" & strModel1 & "', Vic1Year ='" & strYear1 & "', Vic1Color = '" & strColor1 & "'," & _
"Vic2License ='" & strPlate2 & "', Vic2Make ='" & strMake2 & "', Vic2Model ='" & strModel2 & "', Vic2Year ='" & strYear2 & "', Vic2Color = '" & strColor2 & "'," & _
"Vic3License ='" & strPlate3 & "', Vic3Make ='" & strMake3 & "', Vic3Model ='" & strModel3 & "', Vic3Year ='" & strYear3 & "', Vic3Color = '" & strColor3 & "'," & _
"Vic4License ='" & strPlate4 & "', Vic4Make ='" & strMake4 & "', Vic4Model ='" & strModel4 & "', Vic4Year ='" & strYear4 & "', Vic4Color = '" & strColor4 & "'," & _
"Vic5License ='" & strPlate5 & "', Vic5Make ='" & strMake5 & "', Vic5Model ='" & strModel5 & "', Vic5Year ='" & strYear5 & "', Vic5Color = '" & strColor5 & "'," & _
"Vic6License ='" & strPlate6 & "', Vic6Make ='" & strMake6 & "', Vic6Model ='" & strModel6 & "', Vic6Year ='" & strYear6 & "', Vic6Color = '" & strColor6 & "'," & _
" WHERE LastName= '" & strLast & "', AND FirstName= '" & strFirst & "'"

DoCmd.RunSQL strUpdate

2 个答案:

答案 0 :(得分:2)

where子句中不应包含逗号:

" WHERE LastName= '" & strLast & "', AND FirstName= '" & strFirst & "'"
                                   ^--------------------------------------- Remove this

不更新最后一个字段:

Vic6Color = '" & strColor6 & "'," & 
                               ^------------------------------------------- Remove this

您的所有字段(Vic#LicenseVic#MakeVic#ModelVic#Year等)都是字符串值的字段吗?如果没有,您还应该删除填充那些非字符串值的字段的值周围的单引号,例如:

Vic1Year ='" & strYear1 & "',

成为:

Vic1Year =" & strYear1 & ",

但是,尽管上述内容解决了代码的语法问题,但总体而言,出于以下两个原因,我强烈建议避免使用级联变量值来构建SQL查询:

  • 必须将值转换为代表真实字段值的字符串。

  • 如果用户正在提供变量值,则您无法控制所生成的SQL查询的内容,该查询可能会受到SQL注入的影响。

相反,我建议使用parameterising your query来避免上述两种情况。


我也完全同意 @ComputerVersteher 的评论:递增命名的字段清楚地表明数据库设计不佳和缺少database normalisation

假设您的数据库描述了车辆所有权,我个人建议使用三个表:

所有者

+--------------+
| OwnerID (PK) |
| FirstName    |
| LastName     |
+--------------+

车辆

+----------------+
| VehicleID (PK) |
| Make           |
| Model          |
| Plate          |
| Year           |
| Color          |
+----------------+

车辆所有者(连接表)

+----------------+
| ID (PK)        |
| OwnerID (FK)   |
| VehicleID (FK) |
+----------------+

在这里,我在Vehicle-Owners联结表中分配了一个单独的主键字段,该字段允许车辆同时由多个所有者拥有(如果您希望允许这种情况);否则,您可以通过OwnerIDVehicleID的组合来构成主键,以强制拥有车辆的单一所有权。

答案 1 :(得分:-1)

我发现了我的错误。最后一条记录strColor6 & "',"后有一个逗号,一旦删除,该错误就会消失。