且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用JDBC和MySQL释放等待的行,直到其锁定被释放?

更新时间:2023-02-17 17:19:08

您需要如果您不打算更新该行,而只是想确保该行上没有其他事务在运行,请获取意图共享(IS)锁:

If you do not intend to update the row but merely want to ensure that no other transaction is working on the row, obtain an Intention Shared (IS) lock:

SELECT first_name FROM actor WHERE last_name = 'tugay' LOCK IN SHARE MODE

如果打算在结果返回后更新行,请获取Intent eXclusive(IX)锁:

If you intend to update the row after the result comes back, obtain an Intention eXclusive (IX) lock:

SELECT first_name FROM actor WHERE last_name = 'tugay' FOR UPDATE

这两个查询都将阻塞,直到请求的锁可用为止.由于ISIX锁与正在执行或已在行上进行更新(并且尚未提交或回滚)的事务所持有的排他X锁不兼容,因此上述查询中的任何一个都将阻塞,直到其他事务通过提交或回滚释放其X锁.

Both of these queries will block until the requested lock is available. Since IS and IX locks are incompatible with the exclusive X lock held by the transaction that is doing or has done an update on the row (and has not yet committed or rolled back), either of the above queries will block until that other transaction releases its X lock by either committing or rolling back.

然后该事务才获取锁并接收其结果.

Only then does this transaction obtain the locks and receive its result.

最后,该事务最终通过提交或回滚来释放它获得的锁.

Finally, this transaction eventually releases the locks it obtained, by committing or rolling back.

另请参见 https ://dev.mysql.com/doc/refman/5.7/en/innodb-locking.html#innodb-shared-exclusive-locks