gpt4 book ai didi

java - 我可以在 INSERT Batch 之后使用 LAST_INSERT_ID() 进行 SELECT 而不用担心吗?

转载 作者:可可西里 更新时间:2023-11-01 08:51:29 24 4
gpt4 key购买 nike

我在问自己是否可以在 WHERE 子句中使用 LAST_INSERT_ID() 在一批 INSERT 之后进行 SELECT 没有在表中获取损坏的数据?我在考虑多个用户同时做同样事情的场景。我开发了一个 JSF 应用程序,这种情况在其中是可能的。

在硬编码中,我的 SELECTINSERT 之后看起来像这样:

preparedstatement.addBatch(
"INSERT INTO table1(all the FIELDS)"
+ "VALUES(null, ...);"
);

preparedstatement.addBatch(
"INSERT INTO table2(all the FIELDS)"
+ "VALUES(null, LAST_INSERT_ID(), ...);"
);


preparedstatement = connect.prepareStatement(

"SELECT id FROM table3 WHERE id = LAST_INSERT_ID();"

);

preparedstatement.executeBatch();
resultSet = preparedstatement.executeQuery();

这个实现有问题还是有更好的方法?

最好的问候

最佳答案

你应该没问题,引用 MySQL 的文档:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client. This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own. This behavior ensures that each client can retrieve its own ID without concern for the activity of other clients, and without the need for locks or transactions.

MySQL Last_insert_id

关于java - 我可以在 INSERT Batch 之后使用 LAST_INSERT_ID() 进行 SELECT 而不用担心吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13363527/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com