How to cause deadlock on MySQL

给你一囗甜甜゛ 提交于 2019-12-04 12:15:33

问题


For test purposes, I need to generate a "1213: Deadlock" on MySQL so that UPDATE query can't update a table.

I am not not quite sure how to cause deadlock?


回答1:


There are numerous posts for this by using two sessions.

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/

Method copied from the second article above

First, choose an unused table name. I’ll use test.innodb_deadlock_maker. Here are the statements you need to execute:

create table test.innodb_deadlock_maker(a int primary key) engine=innodb;
insert into test.innodb_deadlock_maker(a) values(0), (1);

Now the table and its data are set up. Next, execute the following on two different connections:

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

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



回答2:


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

First Window

BEGIN;
UPDATE table1 SET marks=marks-1 WHERE id=1; -- X lock acquired on 1

Second Window

Update Again

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!

First Window (continued)

UPDATE table1 SET marks=marks+1 WHERE id=2; -- DEADLOCK!
COMMIT;


来源:https://stackoverflow.com/questions/31552766/how-to-cause-deadlock-on-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!