如何保证并发线程在MYSQL中不会获得相同的值? [英] How to guarantee concurrent threads dont get the same value in MYSQL?

查看:84
本文介绍了如何保证并发线程在MYSQL中不会获得相同的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我的订单表中的最后一行是

Lets say the last row in my orders table is

Order_ID      Product
  555          Apple

我如何确定在同一时间发生的2个订单不会得到相同的Order_ID,即下一个订单的556,因为这是我正在发生的事情.我的表使用INNODB.

How can I make sure that 2 orders happening at the exact time wont get the same same Order_ID i.e 556 for the next order because this is what's happening to me. My table uses INNODB.

实际上,Order_ID是一个自动递增的字段.我正在使用显示表​​状态"查询,并使用[自动增量]获取下一个Order_iD.有什么建议吗?

Actually the Order_ID is an auto-increment Field. And I am using the Show Table Status query and using the [Auto-increment] to get the next Order_iD. Any suggestions?

推荐答案

使用Order_ID列. html"rel =" nofollow> AUTO_INCREMENT 属性,并让MySQL为您分配值(成功插入后,您可以通过向驱动程序询问last_insert_id来获取这些值):

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):

ALTER TABLE orders MOFIFY Order_ID BIGINT UNSIGNED NOT NULL AUTO_INCREMENT;

然后,要插入记录,您只需不提供Order_ID值,它将自动被分配:

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

INSERT INTO orders (Product) VALUES ('Apple');

这篇关于如何保证并发线程在MYSQL中不会获得相同的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆