I am trying to get the AutoNumber ID from the most recently entered record in Table X. I was originally using an MS Access database for the backend, and the following VBA code inserted the row and retrieved the correct ID:
Dim db As DAO.Database
Set db = CurrentDb
Dim qdf As DAO.QueryDef
Dim strSql As String
Dim id as long
strSql = "INSERT INTO Table_X (colA, colB, colC)" _
& " VALUES ([colA_val], [colB_val], [colC_val])"
Set qdf = db.CreateQueryDef(vbNullString, strSql)
With qdf
.Parameters("colA_val").Value = colAVal
.Parameters("colB_val").Value = colBVal
.Parameters("colC_val").Value = colCVal
.Execute dbFailOnError
End With
id = db.OpenRecordset("SELECT @@IDENTITY")(0)
However, I moved the MS Access backend to a MySQL backend, and connected the MS Access frontend to it using ODBC. Now, this code runs without errors, but it returns 0 every time for the ID. I manually checked the entry in the Table_X
autonumber ID field, and the ID is set to 800 (for example).
Why is it that id = db.OpenRecordset("SELECT @@IDENTITY")(0)
no longer returns the proper ID after I switched from an MS Access backend to a MySQL backend?
I have tried this as well: id = qdf.OpenRecordset("SELECT @@IDENTITY")(0)
but that gives me the following error:
3421: Data type conversion error.
In summary: how can I get the AutoNumber field for the most recently inserted record in an MS Access frontend connected to a MySQL backend through ODBC?
PS. I have tried the following link: Autonumber value of last inserted row - MS Access / VBA but the DAO method is what I am currently using and is not working.
**EDIT: **
From the link above, I have tried using ADO as well as DAO to insert the records and return the AutoNumber ID. Inserting the records works every time, which means that the connection is successful. However, retrieving the AutoNumber of the last inserted record does not work for both methods. Here is the ADO method I used:
cn.Execute "INSERT INTO TheTable.....", , adCmdText + adExecuteNoRecords
Set rs = cn.Execute("SELECT @@Identity", , adCmdText)
Debug.Print rs.Fields(0).Value
Like I said, the insert works for ADO and DAO so I know that the connection is valid.