如何在没有超时的情况下锁定 Ibm Db2 中的更新行?

How to lock row for update in Ibm Db2 without timeouts?

我需要在 zos 上的 ibm db2 中为每个连接更新一行,而不会出现数据异常。

我选择了FOR UPDATE WITH RS USE AND KEEP语句,但是有问题。如果一个客户端在数据更新期间持有锁,而第二个用户同时尝试读取同一行 - 第二个用户将等待直到锁被释放。

我需要下一个行为:如果行处于锁定状态,第二个用户会收到错误。

在 DB2 11 中可以吗?

你要求的是一个条件 SELECT 如果你能在我正确阅读你的请求的情况下获得 UPDATE 锁。我不相信有办法做到这一点。但是,您可以执行以下操作:

SELECT myCount FROM myTable WHERE ID = someValue

然后您可以更新该值并使用查找 ID 和 myCount 原始值的 WHERE 子句执行 UPDATE。像

这样的序列
SELECT myCount FROM myTable WHERE ID = someValue
origCount = myCount++
UPDATE myTable WHERE ID = someValue AND myCount = origValue

如果您的 UPDATE 显示更新了零行,则表明有人更新了它,然后您重复该序列或继续您的备用逻辑。

我相信这将实现您正在寻找的东西,而不必检测是否存在锁,因为您表示您可以使用 CS 隔离一次访问一行。

这个一般称为Optimistic Concurrency

Optimistic concurrency control (OCC) is a concurrency control method applied to transactional systems such as relational database management systems and software transactional memory. OCC assumes that multiple transactions can frequently complete without interfering with each other. While running, transactions use data resources without acquiring locks on those resources. Before committing, each transaction verifies that no other transaction has modified the data it has read. If the check reveals conflicting modifications, the committing transaction rolls back and can be restarted.[1] Optimistic concurrency control was first proposed by H.T. Kung and John T. Robinson

更新一条记录的时间很长,也许最好只读取包括时间戳的记录,然后处理其他记录。当准备更新时,读取更新,如果时间戳没有改变则更新记录。如果时间戳已更改,则显示错误。