1

我想在 PDO 中对表执行操作之前锁定表,因此两个用户将无法同时执行相同的操作。

我尝试如下:

$this -> link ->beginTransaction();
$this -> link ->exec('LOCK TABLES `MYTABLE` WRITE;');
//do something...
$this -> link ->exec('UNLOCK TABLES');
$this -> link ->commit();

但是如果两个用户尝试这个查询,他们都会堆叠。我做错了什么?

谢谢!!

4

1 回答 1

0
<?php
$this->link->beginTransaction();
$this->link->query('select yourcolumn from yourtable where yourcondition for update');
sleep(20);
$this->link->commit();

然后打开mysql工作台并尝试运行以下

begin;
select count(yourcolumn) from yourtable where yourcondition for update;
// will lock here

请记住在选择列数据时始终打开事务并使用 select 进行更新

当您在工作台中运行以下内容时(在上面的 php 脚本正在运行时),我已经测试了以下内容,这些内容也受锁定保护

update yourtable set yourcolumn=yourvalue where yourcondition;
// will lock here because php has obtained lock, no need to use transaction here

但是,当您在工作台中运行以下内容时(上述 php 脚本正在运行),以下内容不受锁定保护

select yourcolumn from yourtable where yourcondition;
// will immediately return resulset because you are not using transaction AND "for update"

此外,您可以查看所有使用 beginTransaction 的代码,因为长时间运行的事务会导致长表锁定。一个例子是你在一个导入文件操作中只有一个事务。将第一条记录插入表后,表将被锁定。

begin;
insert into yourtable values yourvalues;
// will acquire lock here, other mysql workbench will be deadlock
// until your whole import operation is done and rollback/commit your upload
于 2013-10-21T03:29:39.637 回答