下面的代码应该在transaction表中插入一条记录。代码运行时没有错误,但是在查看事务表时,没有插入新行。
If txtMealID.ItemsSelected.Count = 0 Then
MsgBox "Please Select a Meal Type", _
vbOKOnly + vbInformation
Else
Dim vblMealType As String
vblMealType = txtMealID.Value
MsgBox " " & vblMealType & " ", vbCritical + vbApplicationModal
Set dbs = CurrentDb
Dim qdf As DAO.QueryDef
Set qdf = dbs.CreateQueryDef("", _
"PARAMETERS prmCustomerID Long, prmMealID Text(255), prmTransactionAmount Currency, prmTransactionDate DateTime;" & _
"INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " & _
"VALUES ([prmCustomerID], [prmMealID], [prmTransactionAmount], [prmTransactionDate]) ")
qdf!prmCustomerID = txtCustomerID.Value
qdf!prmMealID = vblMealType
txtCharge.SetFocus
qdf!prmTransactionAmount = txtCharge.Value
qdf!prmTransactionDate = Format(Date, "yyyy-mm-dd")
qdf.Execute dbFailOnError
MsgBox "Customer Charge Succesfull.", _
vbOKOnly + vbInformation
Set qdf = Nothing
Set dbs = Nothing
看来问题出在Set qdf Line上。我的MsgBox“”& vblMealType& “当设置qdf行时,不会触发。
答案 0 :(得分:-1)
您应该测试此变通方法,避免使用DAO查询对象,而是使用DAO :: Database提供的SQL执行。
Private Sub sofInsert20036438_Click()
If txtMealID.ItemsSelected.Count = 0 Then
MsgBox "Please Select a Meal Type", _
vbOKOnly + vbInformation
Else
Dim strSQL As String, vblMealType As String
Dim dbs
vblMealType = txtMealID.Value
MsgBox " " & vblMealType & " ", vbCritical + vbApplicationModal
Set dbs = CurrentDb
'Dim qdf As DAO.QueryDef
'Set qdf = dbs.CreateQueryDef("", _
' "PARAMETERS prmCustomerID Long, prmMealID Text(255), prmTransactionAmount Currency, prmTransactionDate DateTime;" & _
' "INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " & _
' "VALUES ([prmCustomerID], [prmMealID], [prmTransactionAmount], [prmTransactionDate]) ")
'qdf!prmCustomerID = txtCustomerID.Value
'qdf!prmMealID = vblMealType
'txtCharge.SetFocus
'qdf!prmTransactionAmount = txtCharge.Value
'qdf!prmTransactionDate = Format(Date, "yyyy-mm-dd")
'qdf.Execute dbFailOnError
strSQL = "INSERT INTO dbo_Transactions (CustomerID, MealID, TransactionAmount, TransactionDate) " _
& "VALUES (" & txtCustomerID.Value _
& ", '" & vblMealType & "'" _
& ", " & txtCharge.Value _
& ", #" & Format(Date, "yyyy-mm-dd") & "#);"
dbs.Execute strSQL, dbSeeChanges
If (dbs.RecordsAffected > 0) Then
strSQL = "Customer Charge Succesfull."
Else
strSQL = "Error inserting."
End If
'
MsgBox strSQL, vbOKOnly + vbInformation
' Set qdf = Nothing
Set dbs = Nothing
End If
End Sub
这里SQL语法的语法应该使用这些字段定义:
CustomerID: INT,
MealID: VARCHAR(255),
TransactionAmount: FLOAT,
TransactionDate: DATETIME.