对于字段TRX_LOCK_STRUCTS的官方解释如下: The number of locks reserved by the transaction.
会话2: 这个时候在会话2中执行语句会发生阻塞,因为存在相应的锁等待。 select * from test where id=1 for update; 等待一段时间,会话2就会提示超时。 [test]>select * from test where id=1 for update; ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction 这个地方和一个参数是有关联的,innodb_lock_wait_timeout它会控制阻塞等待的时长。 [test]>show variables like '%innodb_lock_wait_timeout%'; | Variable_name | Value | | innodb_lock_wait_timeout | 120 | 对于事务相关的信息查看,在MySQL中有三个比较经典的数据字典,innodb_lock_waits,innodb_trx,innodb_trx,三者可以结合起来,就能够查到相对比较完整的阻塞信息和事务的情况,官方提供的一个SQL如下:
测试死锁 首先给表test添加一条记录 insert into test values(2,'bb'); 为了杜绝表级锁,对表test 添加主键,如果采用下面的方式添加主键,竟然不可以,看来Oracle用惯了,很多思维方式要复制过来,SQL语法还是有不少地方需要注意。 [test]>alter table test modify id primary key; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server vline 1。。。 可以使用下面的方式来添加主键。 [test]>ALTER TABLE test ADD UNIQUE INDEX (id), ADD PRIMARY KEY (id); Query OK, 2 rows affected (0.25 sec) Records: 2 Duplicates: 0 Warnings: 0 接下来来复现一下死锁的情况。
会话1: 开启事务,更新id=1的那行数据。 start transaction; [test]>select * from test where id=1 for update; +----+------+ | id | name | +----+------+ | 1 | aa | +----+------+ 1 row in set (0.00 sec) 这个时候查看innodb_trx的信息,只有1条记录。
会话2: 开启事务,更新id=2的那行数据。 start transaction; select * from test where id=2 for update; (root:localhost:Sat Oct 8 18:15:10 2016)[test]>select * from test where id=2 for update; +----+------+ | id | name | +----+------+ | 2 | bb | +----+------+ 1 row in set (0.00 sec) 这个时候两者是不存在阻塞的情况,因为彼此都是影响独立的行。 >source check_trx.sql Empty set (0.00 sec) 查看事务表,里面就是2条记录了。
会话1: 在会话1中修改id=2的数据行。 select * from test where id=2 for update; 查看事务表,会有一条阻塞的信息。
会话2: 在会话2中修改id=1的数据行,这个时候会发现存在死锁,而MySQL会毫不犹豫的清理掉阻塞的那个会话。这个过程是自动完成的。 [test]>select * from test where id=1 for update; ERROR 1213 (40001): Deadlock found when trying to get lock; try restarting transaction 查看阻塞的信息,就会发现已经被清理掉了。 [(none)]>source check_trx.sql Empty set (0.00 sec) 查看事务表,会发现只有1条记录了。