Skip to content Skip to sidebar Skip to footer

How To Guarantee Concurrent Threads Dont Get The Same Value In Mysql?

Lets say the last row in my orders table is Order_ID Product 555 Apple How can I make sure that 2 orders happening at the exact time wont get the same same Order_I

Solution 1:

I believe that you are 'hardcoding' the order_id + 1...

Please use Auto_increment in your table and it will guarantee you it wont be any order_id repeated

http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html

In your case, make a copy of your table (back-up), alter your table and add an auto_increment then import again

Solution 2:

Define the Order_ID column with the AUTO_INCREMENT attribute and let MySQL assign values for you (that you then retrieve by asking the driver for the last_insert_id after a successful insertion):

ALTERTABLE orders MOFIFY Order_ID BIGINT UNSIGNED NOTNULL AUTO_INCREMENT;

Then, to insert records you simply don't provide an Order_ID value and it will automatically be assigned:

INSERTINTO orders (Product) VALUES ('Apple');

Post a Comment for "How To Guarantee Concurrent Threads Dont Get The Same Value In Mysql?"