[英]Can I SELECT with LAST_INSERT_ID() after INSERT Batch without any cares?
I'm asking myself if it is possible to SELECT
with LAST_INSERT_ID()
in WHERE
Clause after an batch of INSERT
s without getting corrupt data in the tables? 我问自己,在一批
INSERT
之后是否可以在WHERE
子句中使用LAST_INSERT_ID()
进行SELECT
而不会在表中获得损坏的数据? I'm thinking of the scenario that multiple users doing the same stuff at the same time. 我正在考虑多个用户同时做同样事情的场景。 I develop an JSF Application in which this scenario can be possible.
我开发了一个可以实现这种情况的JSF应用程序。
In hard Code my SELECT
after INSERT
s looks like this: 在硬代码中,我在
INSERT
之后的SELECT
看起来像这样:
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();
Get I problems with this implementation or is there an better way? 让我对此实现有疑问,还是有更好的方法?
Best Regards 最好的祝福
You should be fine, quoting MySQL's documentation: 你应该没问题,引用MySQL的文档:
The ID that was generated is maintained in the server on a per-connection basis .
生成的ID在每个连接的基础上在服务器中维护。 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.
这意味着函数返回给定客户端的值是为该客户端影响AUTO_INCREMENT列的最新语句生成的第一个AUTO_INCREMENT值。 This value cannot be affected by other clients, even if they generate AUTO_INCREMENT values of their own.
此值不受其他客户端的影响,即使它们生成自己的AUTO_INCREMENT值。 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.
此行为可确保每个客户端都可以检索自己的ID,而无需关心其他客户端的活动,也无需锁定或事务。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.