【问题标题】:how to test the relevant row in the db table has been locked using postgresql如何测试 db 表中的相关行已使用 postgresql 锁定
【发布时间】:2019-05-30 19:17:16
【问题描述】:

我有一张桌子,我使用 id 锁定它以进行更新。

select name from tablename where id=2 for update

如何测试 db 表中的相关行已被锁定。

【问题讨论】:

    标签: postgresql postgresql-11


    【解决方案1】:

    如果您确定存在id=2 的行,您可以使用:

    select name from tablename where id=2
    for update skip locked
    

    如果结果为空,则表示该行已被其他用户锁定(或不存在)。

    你也可以使用:

    select name from tablename where id=2
    for update nowait
    

    如果该行存在,并且被其他用户锁定,则查询将抛出错误。

    【讨论】:

      【解决方案2】:

      是为了学习或培训目的,如果不是你想要完成的?

      打开两个连接(例如使用“psql”),并在每个连接中运行:

      begin; select name from tablename where id=2 for update;
      

      第二个应该阻塞,直到第一个执行回滚或提交。这种阻塞是锁的证据。有许多变体,其中一个或另一个或两者都可以执行实际的 UPDATE,而不是 SELECT...FOR UPDATE。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-29
        • 1970-01-01
        • 2018-01-19
        相关资源
        最近更新 更多