出于测试目的,我需要在 MySQL 上生成" 1213:死锁" ,以便UPDATE查询无法更新表格。
我不是很确定如何导致死锁?
答案 0 :(得分:5)
通过使用两个会话,有很多帖子。
https://dba.stackexchange.com/questions/309/code-to-simulate-deadlock
http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/
从上面第二篇文章复制的方法
首先,选择一个未使用的表名。我将使用test.innodb_deadlock_maker。以下是您需要执行的语句:
create table test.innodb_deadlock_maker(a int primary key) engine=innodb;
insert into test.innodb_deadlock_maker(a) values(0), (1);
现在设置表及其数据。接下来,在两个不同的连接上执行以下操作:
- 连接0
set transaction isolation level serializable;
start transaction;
select * from test.innodb_deadlock_maker where a = 0;
update test.innodb_deadlock_maker set a = 0 where a <> 0;
- 连接1
set transaction isolation level serializable;
start transaction;
select * from test.innodb_deadlock_maker where a = 1;
update test.innodb_deadlock_maker set a = 1 where a <> 1;
答案 1 :(得分:3)
CREATE TABLE `table1` ( `id` INT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NOT NULL, `marks` INT NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB;
INSERT INTO table1 (id, name, marks) VALUES (1, "abc", 5);
INSERT INTO table1 (id, name, marks) VALUES (2, "xyz", 1);
BEGIN;
UPDATE table1 SET marks=marks-1 WHERE id=1; -- X lock acquired on 1
BEGIN;
UPDATE table1 SET marks=marks+1 WHERE id=2; -- X lock acquired on 2
UPDATE table1 SET marks=marks-1 WHERE id=1; -- LOCK WAIT!
UPDATE table1 SET marks=marks+1 WHERE id=2; -- DEADLOCK!
COMMIT;