Skynight
Skynight

Reputation: 537

Using Auto Increment with MySQL and need to retrieve that number

I have a database in which I need some IDs to be autoincremented, but I also need that ID that gets auto incremented to be the Foreign Key for another table. Is there a way to recover that number within the same transaction to insert values into the second table?

As in: 1) Create a user 2) Retrieve the ID number generated by the auto increment ( for example: AI:5 ) 3) Insert values into a table called Doctor, that needs that number retrieved by that user, all within same transaction...

I know that JSP has some function to recover that ID generated but not sure about MySQL. Another thing is, I can't just send a query to recover the last generated ID because for example if 10 accounts got created at the same time I might not get the supposed number.

Upvotes: 0

Views: 1776

Answers (1)

stivlo
stivlo

Reputation: 85496

For a pure MySQL solution:

SELECT LAST_INSERT_ID();

For a Java way:

ResultSet rs = stmt.getGeneratedKeys();

Upvotes: 3

Related Questions