访问vba更新一个表,多个字段

时间:2017-08-09 19:27:00

标签: sql vba ms-access

帮助,我想用 PARKING_STATUS UPDATED 字段更新我的表 PARKING ,但是我收到了错误消息。我从同一个表中获取所有内容。表单中的所有字段都来自同一个表 PARKING ,PK和FK与其他表。这是代码:

Private Sub Approve_Btn_Click()

    'update data into table(s)
     CurrentDb.Execute "UPDATE PARKING" 
    "SET(parking_id= '" & Me.lot_num_dropdown & "', parking_status = '" & "UPDATED" & "', car_reg_num = '" &    Me.car_reg_num_dropdown & "', result_id = '" & Me.result_id_dropdown & "')" & _
    "WHERE parking_id = '" & Me.lot_num_dropdown & "'"

End Sub

1 个答案:

答案 0 :(得分:1)

考虑使用querydef parameterziation更安全,更清洁,更易维护的版本。不需要引号或字符串连接。

只需将参数值绑定到准备好的SQL语句,该语句也可以是数据库中保存的查询而不是VBA字符串。

Private Sub Approve_Btn_Click()
    Dim qdef As QueryDef

    sql = "PARAMETERS idparam LONG, statusparam TEXT(255), carregparam TEXT(255), resultidparam LONG;" _
           & " UPDATE PARKING SET parking_id = [idparam], parking_status = [statusparam]," _
           & "                    car_reg_num = [carregparam], result_id = [resultidparram]" _
           & " WHERE parking_id = [idparam]"

    ' assign prepared statement to qdef object
     Set qdef = CurrentDb.CreateQueryDef("", sql)  'OR Set qdef = CurrentDb.QueryDefs("mySavedQuery")

     ' bind named parameters
     qdef!idparam = Me.lot_num_dropdown 
     qdef!statusparam = "UPDATED"
     qdef!carregparam = Me.car_reg_num_dropdown  
     qdef!resultidparam = Me.result_id_dropdown

     ' execute action query
     qdef.Execute dbFailOnError

     Set qdef = Nothing
End Sub