Solved

MySQL Last Insert ID

Posted on 2002-07-26
18
1,301 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
ID: 7180051
after you call update just query the adoRs("NameOfIDColumn").Value

0
 
LVL 4

Expert Comment

by:trkcorp
ID: 7180054
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
ID: 7180057
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
ID: 7180061
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
ID: 7180155
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
ID: 7180190
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
ID: 7180200
just open a new recordset using the same connection w/ this sql: "select last_insert_id()"
0
 
LVL 18

Expert Comment

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

Expert Comment

by:gencross
ID: 7180232
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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:dorinda
ID: 7180242
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
ID: 7180267
> 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
ID: 7180274
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
ID: 7180276
> 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
ID: 7180288
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
ID: 7180293
> I tried the last_insert_id() function and it didn't work
what was the error message?
0
 

Author Comment

by:dorinda
ID: 7180360
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
ID: 7180390
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
ID: 7180480
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
Since upgrading to Office 2013 or higher installing the Smart Indenter addin will fail. This article will explain how to install it so it will work regardless of the Office version installed.
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…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

910 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

22 Experts available now in Live!

Get 1:1 Help Now