Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I SELECT with LAST_INSERT_ID() after INSERT Batch without any cares?

Tags:

java

mysql

jdbc

I'm asking myself if it is possible to SELECT with LAST_INSERT_ID() in WHERE Clause after an batch of INSERTs without getting corrupt data in the tables? 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.

In hard Code my SELECT after INSERTs looks like this:

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

like image 486
commandcraxx Avatar asked Nov 30 '25 12:11

commandcraxx


1 Answers

You should be fine, quoting MySQL's documentation:

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

like image 107
Guillaume Avatar answered Dec 03 '25 00:12

Guillaume



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!