开发者

Using Auto Increment with MySQL and need to retrieve that number

开发者 https://www.devze.com 2023-04-09 12:33 出处:网络
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 with

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 valu开发者_运维百科es 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.


For a pure MySQL solution:

SELECT LAST_INSERT_ID();

For a Java way:

ResultSet rs = stmt.getGeneratedKeys();
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号