Row-level and table-level locks, optimistic and pessimistic locks

Since InnoDB defaults to Row-Level Lock, MySQL will only execute Row lock (only lock the selected data) if the primary key is specified explicitly, otherwise MySQL will execute Table Lock (lock the entire data form ).

For example:
Suppose there is a form products with two fields, id and name, and id is the primary key.
Example 1: (Explicitly specify the primary key, and have this data, row lock)

SELECT * FROM products WHERE id='3' FOR UPDATE;

Example 2: (Explicitly specify the primary key, if there is no such data, no lock)

SELECT * FROM products WHERE id='-1' FOR UPDATE;

Example 2: (No primary key, table lock)

SELECT * FROM products WHERE name='Mouse' FOR UPDATE;

Example 3: (primary key is not clear, table lock)

SELECT * FROM products WHERE id<>'3' FOR UPDATE;

Example 4: (primary key is not clear, table lock)

SELECT * FROM products WHERE id LIKE '3' FOR UPDATE;


Optimistic and pessimistic locking strategy
pessimistic locking: lock the few rows when reading data, other updates to these rows need to wait until the end of the pessimistic locking can continue.
Optimistic: When reading data, it is not locked. When updating, check whether the data has been updated. If it is, cancel the current update. Generally, we will choose optimistic locking when the waiting time for the pessimistic lock is too long to accept.

Published 23 original articles · won praise 2 · Views 5235

Guess you like

Origin blog.csdn.net/bianlitongcn/article/details/105530820