Solved

MySQL Last Insert ID

Posted on 2002-07-26
18
1,278 Views
Last Modified: 2007-12-19
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.

0
Comment
Question by:dorinda
  • 6
  • 5
  • 4
  • +3
18 Comments
 
LVL 5

Expert Comment

by:RainUK
Comment Utility
after you call update just query the adoRs("NameOfIDColumn").Value

0
 
LVL 4

Expert Comment

by:trkcorp
Comment Utility
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
 
LVL 17
Comment Utility
In your sql try:

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

0
 
LVL 4

Expert Comment

by:gencross
Comment Utility
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
 

Author Comment

by:dorinda
Comment Utility
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
 
LVL 4

Expert Comment

by:gencross
Comment Utility
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
 
LVL 18

Expert Comment

by:bobbit31
Comment Utility
just open a new recordset using the same connection w/ this sql: "select last_insert_id()"
0
 
LVL 18

Expert Comment

by:bobbit31
Comment Utility
you can also do "select last_insert_id() from <table>"
0
 
LVL 4

Expert Comment

by:gencross
Comment Utility
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 

Author Comment

by:dorinda
Comment Utility
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
 
LVL 18

Expert Comment

by:bobbit31
Comment Utility
> 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
 

Author Comment

by:dorinda
Comment Utility
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
 
LVL 18

Expert Comment

by:bobbit31
Comment Utility
> 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
 
LVL 4

Expert Comment

by:gencross
Comment Utility
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
 
LVL 18

Expert Comment

by:bobbit31
Comment Utility
> I tried the last_insert_id() function and it didn't work
what was the error message?
0
 

Author Comment

by:dorinda
Comment Utility
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
 
LVL 18

Accepted Solution

by:
bobbit31 earned 100 total points
Comment Utility
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
 

Author Comment

by:dorinda
Comment Utility
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

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Suggested Solutions

The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
Background What I'm presenting in this article is the result of 2 conditions in my work area: We have a SQL Server production environment but no development or test environment; andWe have an MS Access front end using tables in SQL Server but we a…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

6 Experts available now in Live!

Get 1:1 Help Now