for update 和 for update nowait的区别

时间:2021-02-02 10:48:35   收藏:0   阅读:0

for update 和 for update nowait的相同点

对操作的数据行进行加锁,在事务提交前防止其他操作对数据的修改

使用for update
测试工具 pgadmin,打开SQL窗口,关闭事务的自动提交,改成手动提交事务
select * from table1 where id =‘001‘ for update;

再用pgadmin打开新的一个SQL窗口,打开事务的自动提交,在执行同样的SQL
select * from table1 where id =‘001‘ for update;

会发现第二个窗口的SQL显示正在查询中,不能出来结果,因为在等待第一个窗口的事务的提交或者回滚

使用for update nowait
测试工具 pgadmin,打开SQL窗口,关闭事务的自动提交,改成手动提交事务
select * from table1 where id =‘001‘ for update nowait;

再用pgadmin打开新的一个SQL窗口,打开事务的自动提交,在执行同样的SQL
select * from table1 where id =‘001‘ for update nowait;

此时第二个窗口的SQL会报错:
ERROR: could not obtain lock on row in relation "table1"
********** 错误 **********

ERROR: could not obtain lock on row in relation "table1"
SQL 状态: 55P03

因为窗口1的SQL事务没提交或者回滚,窗口2的SQL由于不能获取行级锁,报错提示。
业务运用:可以使用在后台防抖防止前台瞬间的连续点击操作,后台在代码中捕获该异常,进行提示即可。

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!