Home > Database > Mysql Tutorial > body text

MySQL锁表的用法,防止并发情况下的重复数据

WBOY
Release: 2016-06-07 17:35:46
Original
1700 people have browsed it

lock table 读锁定 如果一个线程获得在一个表上的read锁,那么该线程和所有其他线程只能从表中读数据,不能进行任何写操作。 loc

lock table 读锁定

如果一个线程获得在一个表上的read锁,那么该线程和所有其他线程只能从表中读数据,不能进行任何写操作。

lock tables user read;//读锁定表

unlock tables;//解锁

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

lock table 写锁定

如果一个线程在一个表上得到一个 write锁,,那么只有拥有这个锁的线程可以从表中读取和写表。其它的线程被阻塞。

lock tables user write;//写锁定表

unlock tables;//解锁

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;
}

linux

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!