3

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

commandcraxx
  • 243
  • 1
  • 7
  • 23
  • Have a look at this page ;) http://stackoverflow.com/questions/4224228/preparedstatement-with-statement-return-generated-keys – Guillaume Nov 13 '12 at 15:29
  • The only thing i saw on this page is to get the Keys from a `connect.preparedStatement()` but in my case i need to get the keys from a batch. – commandcraxx Nov 13 '12 at 16:10
  • Sorry, I misunderstood your question... See the answer below – Guillaume Nov 13 '12 at 16:33

1 Answers1

1

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

Guillaume
  • 14,306
  • 3
  • 43
  • 40