Have an application developed in Access 2010 connected to MySQL Server via ODBC.
I have 2 tables
ContactDetails
with columns:
ID, FirstName, LastName, TelNo, MobileNo, EmailAddress, PrimaryContact, TimeStamp
and ReportingType
with columns:
ID, ReportType, ContactID, TimeStamp
I'm using a ADO transaction but when inserting into ContactDetails
, I need to retrieve the ID so I can insert a corresponding record into ReportingType
and set ReportingType.ContactID
to be ContactDetails.ID
.
In VB.Net I know I can use "Select LAST_INSERT_ID()" at the end of the SQL statement and ExecuteScalar
will return the auto incremented ID
.
Below is my code
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
Please can you help me with this?