您好,我是路人,更多优质文章见个人博客:http://itsoku.com
The select query statement will not be locked, but select.......for update will not only have the function of query, but also lock, and it is a pessimistic lock.
So whether it adds a row lock or a table lock depends on whether the index/primary key is used.
If no index/primary key is used, it is a table lock, otherwise it is a row lock.
verify:
Create table sql
//id为主键
//name 为唯一索引
CREATE TABLE user (
id INT ( 11 ) NOT NULL AUTO_INCREMENT,
name VARCHAR ( 255 ) DEFAULT NULL,
age INT ( 11 ) DEFAULT NULL,
code VARCHAR ( 255 ) DEFAULT NULL,
PRIMARY KEY ( id ),
KEY idx_age ( age ) USING BTREE
) ENGINE = INNODB AUTO_INCREMENT = 1570068 DEFAULT CHARSET = utf8
Automatic submission needs to be turned off, set @@autocommit=0; to manual submission. 0 means manual submission, 1 means automatic submission.
Combine with example verification
Example 1:
Use the primary key id as the condition to query, and then open another transaction to update the data. The update is blocked, locked, and the row data with the id of 1 to be queried is locked.
Figure 1 is the first transaction, and no transaction is committed
Figure 2 shows the second transaction, to update data, is blocked
Figure 3 shows the second transaction, where the lock was not obtained for a long time and an error was reported.
Example 2:
We are starting a transaction to update another piece of data with id 2,
Example 3 (index):
At the beginning of creating the table, a unique index was created on age.
Example 4:
Use common field codes to operate
In another transaction, I will update another piece of data. If the update is successful, it will lock the row, and if it fails, it will lock the table.
result:
If the query condition uses an index/primary key, then select ..... for update will lock the row.
If it is an ordinary field (no index/primary key), then select ..... for update will lock the table.
more good articles
Talk about common implementations of db and cache consistency
Interface idempotence is so important, what is it? How to achieve it?
↓↓↓ 点击阅读原文,直达个人博客
你在看吗