Optimistic locking is a practice used in concurrency control to prevent multiple users from updating the same data simultaneously. Unlike pessimistic locking, which assumes that conflicts will occur and locks data at the beginning of a transaction, optimistic locking assumes that conflicts are rare and allows updates without locking.
MySQL does not natively implement optimistic locking. However, it can be implemented using standard SQL instructions and the version column approach:
<code class="sql">CREATE TABLE theTable ( id INT NOT NULL AUTO_INCREMENT, val1 INT NOT NULL, val2 INT NOT NULL, version INT NOT NULL DEFAULT 0 );</code>
Optimistic Locking Query:
<code class="sql">UPDATE theTable SET val1 = @newVal1, val2 = @newVal2, version = version + 1 WHERE id = @id AND version = @oldVersion;</code>
Checking for Conflicts:
After the update, the AffectedRows value is checked:
Transaction isolation levels play a role in optimistic locking. In READ_COMMITTED isolation level, other processes cannot read uncommitted updates, which prevents conflicts from occurring.
Optimistic locking is suitable for situations with infrequent updates and a low probability of conflicts. It is often used in web applications where short user sessions reduce the likelihood of concurrent updates.
The above is the detailed content of How Can You Implement Optimistic Locking in MySQL?. For more information, please follow other related articles on the PHP Chinese website!