首頁  >  問答  >  主體

mysql 为何insert的时候会有lock wait timeout 异常

执行单元测试(mvn clean test)时偶尔会遇到下面的异常信息

org.springframework.dao.CannotAcquireLockException:

### Error updating database.  Cause: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
### The error may involve com.foo.dao.mapper.TestMapper.insertSuccesfulPaymentOrder-Inline
### The error occurred while setting parameters
### SQL: insert into order(order_seq,note,user_id,product_id, pay_status) values(uuid(),'',?,?,1)
### Cause: java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction
; SQL []; Lock wait timeout exceeded; try restarting transaction; nested exception is java.sql.SQLException: Lock wait timeout exceeded; try restarting transaction

但是像这样的错误 不应该只是update才会有吗? 见官方文档说明

A transaction that tries to access a row that is locked by another InnoDB transaction waits at most this many seconds for write access to the row before issuing the following error:

ERROR 1205 (HY000): Lock wait timeout exceeded; try restarting transaction

但我明明是insert啊。 并且还只是偶尔会有这种情况, 且稍后就正常了。

所以不明白到底是怎么回事? 怎么模拟这种情况呢?

PHPzPHPz2743 天前703

全部回覆(1)我來回復

  • 高洛峰

    高洛峰2017-04-17 14:58:40

    我相信你已經知道此種現像是發生鎖表了,lock wait timeout 意思就是由於鎖表導致事務等待的時間過長,然後事務回滾了
    我想你的疑問是(為什麼insert操作會鎖表)。

    我的解釋如下:
    一般來說在普通狀態下,是不會發生此現象的,但是你主動啟動了事務(或者不主動提交事務)就不同了,由於事務運行是需要一定時間並且將有多條指令運行,那麼在此情況下,如果另外一個進程也開啟了事務並且鎖了表,並且無法短時間運行完的話(默認記得是50秒),那麼第一條事務會報這樣的錯並且回滾。
    所以他在錯誤中提示你try restarting transaction;讓你重新執行

    回覆
    0
  • 取消回覆