Search code examples
mysqlvb.nettableadapter

Last_Insert_Id issues using TableAdapter with MySQL


I am having an issue using Last_Insert_Id in a VB.NET TableAdapter Insert query wired to a MySQL database. I've read through numerous posts on this site and others regarding Last_Insert_ID and Scope_Identity, etc. None of which have worked in my case.

A little background, I have two tables, one holds login information (Auto-generated ID, username, password). Another table has a foreign key relationship on the ID values and contains ID, first name, last name, city, state.

In my TableAdapter I have an Insert query that inserts values into the first table and is supposed to return the ID value so that an Insert can be done on table 2.

Here is my Query:

INSERT INTO user_logins (user_login, user_pass)  
VALUES (@p1, @p2)

I wanted to add Last_Insert_Id to make the query

INSERT INTO user_logins (user_login, user_pass)
VALUES (@p1, @p2)
SELECT LAST_INSERT_ID();

However that will only return a value of 1, regardless of what the ID is. If I open the Query Builder I get a message that states "Unable to parse query text". I tried changing the ExecuteMode to Scalar, but that didn't help either.

The Insert part is working perfectly, if I could only obtain the ID value back after insert.

Does anyone know anything I might try, or alternatively, some better way to achieve this?

Thanks!


Solution

  • You don't even need to use SELECT LAST_INSERT_ID(); just INSERT INTO user_logins (user_login, user_pass) VALUES (@p1, @p2) is OK To retrieve last insert Id you can use two ways

    Dim t As Integer
    cmd.ExecuteNonQuery()
    t = (Int32) cmd.LastInsertedId
    

    OR

    t = Convert.ToInt32(cmd.ExecuteScalar())