MySQL lock table usage to prevent repeated data under concurrent conditions

Source: Internet
Author: User
Locktable read lock if a thread obtains the read lock on a table, the thread and all other threads can only read data from the table and cannot perform any write operations. Loc

Lock table read lock if a thread obtains the read lock on a table, the thread and all other threads can only read data from the table and cannot perform any write operations. Loc

Lock table read lock

If a thread acquires a read lock on a table, the thread and all other threads can only read data from the table and cannot perform any write operations.

Lock tables user read; // read the locked table

Unlock tables; // unlock

Lock tables user read local; // The local read locks the table. The insert statements of other threads are not blocked, and the update operation is blocked.

Lock table write lock

If a thread gets a write lock on a table, only the thread that owns the lock can read and write tables from the table. Other threads are blocked.

Lock tables user write; // write to lock the table

Unlock tables; // unlock

Usage instance in Yii

/**
* Single content status on the current day
*/
Public function getPointAready ($ marke, $ dayTime ){
$ Model = SysRun: model ()-> findByAttributes (array ('syr _ marking' => $ marke, 'syr _ daytime' => $ daytime ));
If (empty ($ model )){
// Table write lock
Yii: app ()-> db-> createCommand ()-> setText ("lock tables {sys_run} WRITE")-> execute ();
$ Model = new SysRun ();
$ Model-> syr_marking = $ marke;
$ Model-> syr_daytime = $ dayTime;
$ Model-> syr_val = 0;
$ Model-> syr_subval = 0;
$ Model-> save ();
// Unlock a table
Yii: app ()-> db-> createCommand ()-> setText ("unlock tables")-> execute ();
}
Return $ model;
}

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.