Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
?
Solved

MySQL Last Insert ID

Posted on 2002-07-26
18
Medium Priority
?
1,472 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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
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
 

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 400 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

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
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…
Suggested Courses

580 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