Home  >  Article  >  php教程  >  Yii+MYSQL lock table method to prevent duplicate data under concurrency

Yii+MYSQL lock table method to prevent duplicate data under concurrency

高洛峰
高洛峰Original
2017-03-30 15:17:522354browse

The example of this article describes the method of Yii+MYSQL lock table to prevent duplicate data in concurrent situations. Share it with everyone for your reference, as follows:

lock table read lock

If a thread obtains a read lock on a table, then the thread and all other threads can only read locks from the table Read data, no write operations can be performed.

lock tables user read;//读锁定表
unlock tables;//解锁
lock tables user read local;//本地读锁定表,其他线程的insert未被阻塞,update操作被阻塞

lock table write lock

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

lock tables user write;//写锁定表
unlock tables;//解锁

Usage examples in Yii

/**
* 当日单项内容状态
*/
public function getPointAready($marke,$dayTime){
  $model = SysRun::model()->findByAttributes(array('syr_marking'=>$marke,'syr_daytime'=>$dayTime));
  if(empty($model)){
    //表写锁定
    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();
    //表解锁
    Yii::app()->db->createCommand()->setText("unlock tables")->execute();
  }
  return $model;
}

I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.

For more related articles on how Yii+MYSQL locks tables to prevent duplicate data under concurrency, please pay attention to the PHP Chinese website!

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