mysql 查找死锁并解锁
时间: 2023-12-12 07:24:39 浏览: 156
mysql 数据库死锁原因及解决办法
5星 · 资源好评率100%
在 MySQL 中,可以通过以下步骤进行死锁查找和解锁:
1. 查找死锁:
```sql
SHOW ENGINE INNODB STATUS;
```
执行以上命令,可以看到类似如下的输出:
```
------------------------
LATEST DETECTED DEADLOCK
------------------------
2019-11-11 10:47:09 0x7f3c9e2a1700
*** (1) TRANSACTION:
TRANSACTION 210885, ACTIVE 0 sec starting index read
mysql tables in use 1, locked 1
LOCK WAIT 5 lock struct(s), heap size 1184, 2 row lock(s)
MySQL thread id 110, OS thread handle 139777748852992, query id 2726972 localhost root updating
UPDATE `users` SET `name`='Alice', `age`=30 WHERE `id`=1
*** (1) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 1 page no 3 n bits 72 index PRIMARY of table `test`.`users` trx id 210885 lock_mode X locks rec but not gap waiting
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000001; asc ;;
1: len 6; hex 0000020d423d; asc =B=;;
2: len 7; hex 00000000000210; asc ;;
*** (2) TRANSACTION:
TRANSACTION 210886, ACTIVE 0 sec inserting
mysql tables in use 1, locked 1
5 lock struct(s), heap size 1184, 2 row lock(s), undo log entries 1
MySQL thread id 111, OS thread handle 139777748919296, query id 2726973 localhost root update
INSERT INTO `users` (`name`, `age`) VALUES ('Bob', 25)
*** (2) HOLDS THE LOCK(S):
RECORD LOCKS space id 1 page no 3 n bits 72 index PRIMARY of table `test`.`users` trx id 210886 lock_mode X locks rec but not gap
Record lock, heap no 2 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000001; asc ;;
1: len 6; hex 0000020d423d; asc =B=;;
2: len 7; hex 00000000000210; asc ;;
*** (2) WAITING FOR THIS LOCK TO BE GRANTED:
RECORD LOCKS space id 1 page no 3 n bits 72 index PRIMARY of table `test`.`users` trx id 210886 lock_mode X locks rec but not gap waiting
Record lock, heap no 3 PHYSICAL RECORD: n_fields 3; compact format; info bits 0
0: len 4; hex 80000002; asc ;;
1: len 6; hex 0000020d423e; asc =B>;;
*** WE ROLL BACK TRANSACTION (2)
```
在输出中,可以看到 LATEST DETECTED DEADLOCK,其中包含了死锁发生的信息。
2. 解锁:
根据上面的输出,可以看到死锁发生在 `test`.`users` 表中的记录上,可以通过如下命令来解锁这个记录:
```sql
SELECT * FROM `information_schema`.`innodb_locks` WHERE `LOCK_TABLE` = 'users' AND `LOCK_INDEX` = 'PRIMARY' AND `LOCK_TRX_ID` = 210885;
```
上述命令可以查询到锁定了这个记录的事务的 ID 是 210885,接下来可以使用如下命令来杀死这个事务:
```sql
KILL 210885;
```
这样就可以解锁这个记录。需要注意的是,杀死事务可能会导致数据不一致,需要谨慎操作。
阅读全文