Home > Database > Mysql Tutorial > body text

关于mysql事务行锁forupdate实现写锁的功能_MySQL

WBOY
Release: 2016-06-01 13:17:40
Original
1047 people have browsed it

在电子商务里,经常会出现库存数量少,购买的人又特别多,大并发情况下如何确保商品数量不会被多次购买.

其实很简单,利用事务+for update就可以解决.

我们都知道for update实际上是共享锁,是可以被读取的.但是如何在执行时,不被读取呢.

简单来说:假设现在库存为1,现在有A和B同时购买

先开启一个事务

begin;

select stock from good where id=1 for update;//查询good表某个商品中stock的数量

查出来后,在程序里在判断这个stock是否为0(你用什么语言,不关我事)

最后在执行

update good set stock=stock-1 where id=1

最后在

commit

但是这个时候B也是select stock from good where id=1 for update;注意:for update不能省略..这个时候会出现被锁住,无法被读取.

所以这就能够保证了商品剩余数量为1的一致性.

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!