8
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.

John Nuñez
  • 1,780
  • 13
  • 35
  • 51
  • Are you actually passing an ID as the query suggests? Or is it really an auto-increment? In MySQL you can select `LAST_INSERT_ID` to get the last auto-incremented ID in a transaction. – David Mar 20 '12 at 16:50
  • No, THe id is generated by MySQL, i only pass the status code – John Nuñez Mar 20 '12 at 16:57

3 Answers3

14

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)
blackriderws
  • 833
  • 2
  • 9
  • 14
  • Never thought we could use a double query in vb.net sql statement. It helps to get the auto-increment number from ID column. Thank you. – surpavan Nov 30 '16 at 18:27
2

Bit late to the party but after

cmd_query.ExecuteScalar()
MsgBox(cmd_query.LastInsertedId)

Produces the last insert id.

1

You can fetch the AUTO_INCREMENT value for a table through a MySQL query and then show that in your MsgBox

Community
  • 1
  • 1
sikander
  • 2,286
  • 16
  • 23