Mysql lock mechanism -- row lock

 

Mysql series article home page 

 

===============

 

1 Prepare data

1.1 Create a table

DROP TABLE IF EXISTS employee;
CREATE TABLE IF NOT EXISTS employee (
    id INT PRIMARY KEY auto_increment,
    name VARCHAR(40),
        money INT
)ENGINE INNODB;

Note: ENGINE is INNODB (because InnoDB only supports row locks)

1.2 Insert data

INSERT INTO employee(name, money) VALUES('Alice', 10000);
INSERT INTO employee(name, money) VALUES('Bob', 10000);

2 test

2.1 Preparation before the test

  • Prepare two sessions (terminal, command line), one white (marked: left) and one black (marked: right)
  • Both sessions set autocommit=0

The command is as follows:

SET autocommit = 0;

Result of execution in left session:

Result of execution in right session:

2.2 Update different rows

2.2.1 Testing

Step 1: Execute in the left session

UPDATE employee SET money = money + 10000 WHERE id = 1;

Step 2: Execute in the right session

UPDATE employee SET money = money + 5000 WHERE id = 2;

It can be seen that the left and right sessions can be executed separately at the same time without affecting each other.

Step 3: Submit both terminals

Step 4: Query the two terminals separately

SELECT * FROM employee; 

The result is that the query results of the two terminals are the same, and the two database records are the results updated by the two terminals respectively (10000+10000=20000, 10000+5000=15000).

2.2.2 Conclusion

For InnoDB's default row locks, if different rows are updated, they can operate at the same time without affecting each other.

2.3 Update the same row

2.3.1 Testing

Step 1: Execute in the left session

UPDATE employee SET money = money + 10000 WHERE id = 1; 

Step 2: Execute in the right session

UPDATE employee SET money = money - 1000 WHERE id = 1;

As you can see, the Sql statement is suspended (blocked)!

Step 3: Execute COMMIT on the left (note the changes in the execution of the Sql statement in the session on the right)

Step 4: Pay attention to the conversation on the right

Step 5: Execute COMMIT on the right

Step 6: View the results on the left

Step 7: Check the results on the right

It can be seen that the results on the left and right sides are the same and correct (20000+10000=30000-1000=29000)

2.3.2 Conclusion

InnoDB row lock, when updating the same row, the update operation of the latter session will be blocked (suspended) before the previous session is committed, and the latter update operation cannot be performed until the previous session is committed.

3 Conclusion

InnoDB row locks will not affect each other when updating different rows, and will only block when updating the same row.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324766546&siteId=291194637