About MySQL transaction row lock forupdate to realize write lock function

Source: Internet
Author: User

In E-commerce, there will often be a small number of inventory, the purchase of the person is particularly large, concurrency in the case of how to ensure that the number of goods will not be purchased multiple times.

In fact very simple, use the transaction +for update can be solved.

We all know that for update is actually a shared lock that can be read. But how to execute it without being read.

To put it simply: Assuming inventory is now 1, now there is a and B at the same time purchase

Open a transaction first

Begin

Select the good where id=1 for update;//query Good the number of stock in a product

After checking out, in the program to determine whether the stock is 0 (what language you use, not my business)

Finally in the implementation

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

Finally in

Commit

But this time B is also select the stock from good where id=1 for update; Note: For update cannot omit ... This time will appear to be locked, unable to be read.

So this will ensure that the number of goods remaining 1 of the consistency.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.