MySQL Last Insert ID

Can anyone tell me how to write or get the last auto increment id in VB.  I am using mysql, ado, odbc.

I am doing an .AddNew and then .Update and then in the next step I need to know what the auto id was so I can pass it to another form.

dorindaAsked:
Who is Participating?
 
bobbit31Connect With a Mentor Commented:
If you get the error [Microsoft][ODBC Driver Manager] Driver does not support this parameter the reason may be that you have a BIGINT in your result. Try setting the Change BIGINT columns to INT option in the MyODBC connect screen.

also make sure you have the most recent myodbc driver
0
 
RainUKCommented:
after you call update just query the adoRs("NameOfIDColumn").Value

0
 
trkcorpCommented:
Well, I don't know about MySQL but in SQL Server you can do the insert inside a stored procedure and have the stored procedure return the ID. Like:

CREATE PROC cp_Insert_and_return_ID
AS
BEGIN
     INSERT table_name (Field1) VALUES('Value')
     SELECT @@IDENTITY AS ID
     RETURN
END
GO
0
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
Thibault St john Cholmondeley-ffeatherstonehaugh the 2ndCommented:
In your sql try:

INSERT INTO tablename (id, stuff) VALUES(tablenameSeq.nextval, stuffvalue)
RETURNING ID INTO v_lastupdateID;

0
 
gencrossCommented:
After the addnew or update call check the auto id field, it may be populated with the next ID

.Update
AutoID = .Fields("ID")

I have not tested this, but it  work.  If not you can retrieve it using a SQL statement.  Here is the function I use...

Public Function ReturnLastAutoNumber(sTableName As String) As Long
   
    Dim rstTemp As adodb.Recordset
     
    Set rstTemp = objDBConn.Execute("select max(IDENTITYCOL) as Col from " & sTableName)

    ReturnLastAutoNumber = rstTemp!Col
   
    rstTemp.Close
   
End Function

NOTE: If you have multiple users adding records this could return the ID of a record that was added by another user.
0
 
dorindaAuthor Commented:
gencross, Thanks a million!! I had to use the select max statement...but I will have multiple people adding records so what would you recommend.  Here is what I ended up with.

 
Set adoLog3000Rule = New Recordset
    adoLog3000Rule.Open "SELECT MAX(Log3000ID) as col FROM Log3000", _
      db, adOpenKeyset, adLockOptimistic, adCmdText
    adoLog3000Rule.MoveFirst
    gbl_Highlighted_Log3000ID = Val(adoLog3000Rule.Fields(0))
     
0
 
gencrossCommented:
In the past with multiple users I have added a record with a date time stamp and user id then select the record from the table using the date time stamp as well as the user who entered the record.

Here is an example of using just a date time, but you can add a user id to it.  Alternatively you can select the record using other unique data.  You would think there is an easier way to do this, but there isn't:)

sNow = Now

.AddNew
.DateAdded = sNow
.Update

Retrieve ID...

sSQL = "SELECT ID FROM Table WHERE DateAdded = '" & sNow & "'"

Let me know if this makes sense.
0
 
bobbit31Commented:
just open a new recordset using the same connection w/ this sql: "select last_insert_id()"
0
 
bobbit31Commented:
you can also do "select last_insert_id() from <table>"
0
 
gencrossCommented:
bobbit, multiple users are adding records at the same time.  Is using the last_insert_id function going to return the ID of the particular record that was added or the ID of the last record that was added?
0
 
dorindaAuthor Commented:
I tried the last_insert_id() function and it didn't work...is this function suppose to work with mysql, odbc, VB, and ado combination?
0
 
bobbit31Commented:
> multiple users are adding records at the same time

from mysql docs:

LAST_INSERT_ID([expr])
Returns the last automatically generated value that was inserted into an AUTO_INCREMENT column. See section 8.4.3.126 mysql_insert_id().
mysql> SELECT LAST_INSERT_ID();
        -> 195

The last ID that was generated is maintained in the server on a per-connection basis. It will not be changed by another client. It will not even be changed if you update another AUTO_INCREMENT column with a non-magic value (that is, a value that is not NULL and not 0). If you insert many rows at the same time with an insert statement, LAST_INSERT_ID() returns the value for the first inserted row. The reason for this is so that you it makes it possible to easily reproduce the same INSERT statement against some other server. If expr is given as an argument to LAST_INSERT_ID(), then the value of the argument is returned by the function, and is set as the next value to be returned by LAST_INSERT_ID().
0
 
dorindaAuthor Commented:
Here is what works...

adoLog3000Rule.Open "SELECT MAX(Log3000ID) as col FROM Log3000", _
'            db, adOpenKeyset, adLockOptimistic, adCmdText

But is there anyway to add the RecordAdded col to this same select with a WHERE clause also to compare against the worktime.
For example:

  adoLog3000Rule.Open "SELECT MAX(Log3000ID) as col from Log3000, Log3000.RecordAdded WHERE RecordAdded = " & "'" & worktime & "',""" _
            db, adOpenKeyset, adLockOptimistic, adCmdText


Can anyone help with the syntax of this....
0
 
bobbit31Commented:
> mysql, odbc, VB, and ado combination?

i see no reason why it wouldn't...
mysql is the only thing that needs to understand it.
0
 
gencrossCommented:
You should not need to use the max function in this statement.  Try this...

(You will probably only want to open the recordset forward only also)

set adoLog3000Rule = db.Execute("SELECT Log3000ID as col from Log3000 WHERE RecordAdded = " & "'" & worktime & "'"
0
 
bobbit31Commented:
> I tried the last_insert_id() function and it didn't work
what was the error message?
0
 
dorindaAuthor Commented:
The error was "ODBC driver manager driver does not support this parameter"  This was my statement...

adoLog3000Rule.Open "SELECT LAST_INSERT_ID()", db, adOpenForwardOnly, adLockOptimistic, adCmdText
0
 
dorindaAuthor Commented:
THANKS TO EVERYONE FOR ALL YOUR HELP... I HAVE LEARNED LOTS!  SETTING THE BIGINT TO INT OPTION FIXED IT.  I WAS ABLE TO USE THE LAST_INSERT_ID FUNCTION.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.