【发布时间】:2017-09-20 14:38:12
【问题描述】:
让在 Access 2010 中开发的应用程序通过 ODBC 连接到 MySQL 服务器。
我有两张桌子
ContactDetails 带列:
ID, FirstName, LastName, TelNo, MobileNo, EmailAddress, PrimaryContact, TimeStamp
和ReportingType 与列:
ID, ReportType, ContactID, TimeStamp
我正在使用 ADO 事务,但在插入 ContactDetails 时,我需要检索 ID,以便将相应的记录插入 ReportingType 并将 ReportingType.ContactID 设置为 ContactDetails.ID。
在 VB.Net 中,我知道我可以在 SQL 语句末尾使用“Select LAST_INSERT_ID()”,ExecuteScalar 将返回自动递增的ID。
下面是我的代码
Dim conn As ADODB.Connection
On Error GoTo ErrorHandler
Set conn = CurrentProject.Connection
With conn
.BeginTrans
'insert a new customer record
.Execute "INSERT INTO ContactDetails (" & _
"FirstName, " & _
"LastName , " & _
"TelNo , " & _
"MobileNo ," & _
"EmailAddress ," & _
"IsPrimaryContact) " & _
"Values ( " & _
"'" & Me.FirstName & "'," & _
"'" & Me.LastName & "'," & _
"'" & Me.TeleNum & "'," & _
"'" & Me.MobileNum & "'," & _
"'" & Me.EmailAddress & "'," & _
False & ");", , adCmdText + adExecuteNoRecords
'Added from a possible solution
Dim rs As New ADODB.Recordset
Set rs = conn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value ' This returned 0
'Inset a new record into the ReportingType Table
For i = 1 To ListView1.ListItems.Count
If ListView1.ListItems(i).Checked Then
.Execute "INSERT INTO ReportingType " & _
"(ReportType, ContactID) " & _
"VALUES " & _
"('" & colReportType(ListView1.ListItems(i)) & "' , " & ContactID & ")"
End If
Next i
.CommitTrans
End With
ExitHere:
Set conn = Nothing
Exit Sub
ErrorHandler:
If Err.Number = -2147467259 Then
MsgBox Err.Description
Resume ExitHere
Else
MsgBox Err.Description
With conn
.RollbackTrans
'.Close
End With
Resume ExitHere
End If
End Sub
你能帮我解决这个问题吗?
【问题讨论】:
-
您可以在写入数据后查询
Contact Details以返回最新的ID值(通过ADODB.RecordSet)并在下一个INSERT INTO语句中使用它 -
感谢您的链接。在最后插入的行的帖子自动编号值 - MS Access / VBA 我添加了以下 ater 我的第一个 .Execute Dim rs As New ADODB.Recordset Set rs = conn.Execute("SELECT LAST_INSERT_ID()", , adCmdText) Debug.Print rs.Fields(0).Value 但是 rs.Fields(0).Value 返回零 (0)
标签: vba ms-access transactions ado