运行时错误3061预期的参数太少4

时间:2018-05-02 19:27:12

标签: sql ms-access access-vba

CurrentDb.Execute "UPDATE Customer set [FirstName] = " & Me.FirstName & _
                                    " ,[LastName] = " & Me.LastName & _
                                    " ,[PhoneNumber] = '" & Me.PhoneNumber & _
                                    "' ,[Address] = '" & Me.Address & _
                                    "' ,[City] = " & Me.City & _
                                    " ,[State] = " & Me.State & _
                                    " ,[ZipCode] = " & Me.ZipCode & " WHERE ([E-mail] = '" & Me.email & "')"

此更新查询有什么问题。请帮忙。

2 个答案:

答案 0 :(得分:2)

再次考虑SQL参数化,这是使用SQL时的行业最佳实践,使用PARAMETERS子句和QueryDefs在MS Access中支持 。你可以避免凌乱的连接,引用附件(你的文本字段相当缺少),以及可能的SQL注入,因为这些字段对用户开放。

SQL (另存为存储的Access查询)

PARAMETERS [FirstNameParam] Text(255), [LastNameParam] Text(255),
           [PhoneNumberParam] Text(255), [AddressParam] Text(255),
           [CityParam] Text(255), [StateParam] Text(255),
           [ZipCodeParam] Text(255), [EmailParam] Text(255);
UPDATE Customer 
   SET [FirstName] = [FirstNameParam],
       [LastName] = [LastNameParam],
       [PhoneNumber] = [PhoneNumberParam],
       [Address] = [AddressParam],
       [City] = [CityParam],
       [State] = [StateParam],
       [ZipCode] = [ZipCodeParam]
WHERE ([E-mail] = [EmailParam]);

<强> VBA

Dim qdef As QueryDef

Set qdef = CurrentDb.QueryDefs("mySavedParameterQuery")

' BIND VALUES TO PARAMETER PLACEHOLDERS
qdef![FirstNameParam] = Me.FirstName
qdef![LastNameParam] = Me.LastName
qdef![PhoneNumberParam] = Me.PhoneNumber
qdef![AddressParam] = Me.Address
qdef![CityParam] = Me.City
qdef![StateParam] = Me.State
qdef![ZipCodeParam] = Me.ZipCode
qdef![EmailParam] = Me.Email

' EXECUTE ACTION QUERY
qdef.Execute dbFailOnError

Set qdef = Nothing

答案 1 :(得分:1)

只是猜测你的SQL和错误 - 我怀疑你的两个单词的4个字段名称可能在这两个单词之间有空格:[FirstName]变为[First Name][Last Name]变为[Last Name]等等

所以SQL字符串实际应该是

"UPDATE Customer set [First Name] = " & Me.FirstName & _
                                        " ,[Last Name] = " & Me.LastName & _
                                        " ,[Phone Number] = '" & Me.PhoneNumber & _
                                        "' ,[Address] = '" & Me.Address & _
                                        "' ,[City] = " & Me.City & _
                                        " ,[State] = " & Me.State & _
                                        " ,[Zip Code] = " & Me.ZipCode & " WHERE ([E-mail] = '" & Me.email & "')"

正如@ Jiggles32所说 - 唯一可以确定的方法是向客户表显示您的字段名称