Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Last ID (IDENTITY) On Insert row VB.NET MySQL

Dim insert_coupon_query As String = ("INSERT INTO qa_discountcoupons (id, status_code) VALUES (AUTO_INCREMENT_ID, 5)")
                Dim cmd_query As New MySqlCommand(insert_coupon_query, objConn)
                Dim cmd_result As Integer = CInt(cmd_query.ExecuteScalar())

I want to return the AUTO_INCREMENT value of the current insert, and show in a msgbox.

like image 528
John Nuñez Avatar asked Mar 20 '12 16:03

John Nuñez


People also ask

How to get the unique ID for the last inserted row?

MySQL 8.0 C API Developer Guide / ... / Obtaining the Unique ID for the Last Inserted Row If you insert a record into a table that contains an AUTO_INCREMENT column, you can obtain the value stored into that column by calling the mysql_insert_id () function.

How do I get last insert ID in SQL?

select last_insert_id (); Code language: SQL (Structured Query Language) ( sql ) As you can see clearly from the output, the LAST_INSERT_ID() function returns the generated value of the first row successfully inserted, not the last row.

How to use MySQL last_insert_ID function?

Let’s look at an example of using MySQL LAST_INSERT_ID function. First, create a new table named messages for testing. In the messages table, we set the AUTO_INCREMENT attribute for the id column. Second, insert a new row into the messages table. Third, use the MySQL LAST_INSERT_ID function to get the inserted value of the id column:

How to get the last value of the ID column in MySQL?

Code language:SQL (Structured Query Language)(sql) Second, insert a new row into the messagestable. INSERTINTOmessages(description) VALUES('MySQL last_insert_id'); Code language:SQL (Structured Query Language)(sql) Third, use the MySQL LAST_INSERT_IDfunction to get the inserted value of the idcolumn: SELECTLAST_INSERT_ID();


1 Answers

You can use an double Query and use the function LAST_INSERT_ID() After run your first query to get the last current query:

Dim insert_coupon_query As String = ("INSERT INTO qa_discountcoupons (status_code) VALUES (5); SELECT LAST_INSERT_ID()")
                Dim cmd_query As New MySqlCommand(insert_coupon_query, objConn)
                Dim cmd_result As Integer = CInt(cmd_query.ExecuteScalar())

                MsgBox(cmd_result)
like image 102
blackriderws Avatar answered Sep 22 '22 17:09

blackriderws