Mysql series article home page
===============
1 Prepare data
1.1 Create a table
1.1.1 Create the Employee table
DROP TABLE IF EXISTS employee; CREATE TABLE IF NOT EXISTS employee ( id INT PRIMARY KEY auto_increment, name VARCHAR(40), dept_id INT )engine myisam;
1.1.2 Create the Department table
DROP TABLE IF EXISTS department; CREATE TABLE IF NOT EXISTS department ( id INT PRIMARY KEY auto_increment, name VARCHAR(40) )engine myisam;
1.1.3 Note: The storage engines of the above two tables are MyISam
1.2 Insert data
INSERT INTO employee(name, dept_id) VALUES('Alice', 1); INSERT INTO employee(name, dept_id) VALUES('Bob', 1);
INSERT INTO department(name) VALUES('RD');
2 test
2.1 Add a write lock to the Employee table
LOCK TABLE employee WRITE;
2.2 Query the Employee table
2.2.1 Current session (terminal, command line window)
Note: The current session refers to the session (window, command line) that executed the LOCK TABLE employee READ statement above; in my case, the white background.
SELECT * FROM employee;
2.2.2 Other sessions (terminal, command line window)
Note: Open a new session window; in my case, a black background.
Queries all block (hang)!
Unlock in 'current session'
After unlocking, 'other sessions' can be queried normally!
2.2.3 Conclusion
It can be seen that after the write lock is added, the current session can be queried, but other sessions cannot be queried.
2.3 Update the Employee table
2.3.0 Preparation
Re-add a write lock to the Employee table
LOCK TABLE employee WRITE;
2.3.1 Current session
UPDATE employee SET name = 'Alice02' WHERE id = 1;
2.3.2 Other sessions
Still blocked!
Unlock the current session
Can only be updated after unlocking
2.3.3 Conclusion
It can be seen that after adding the write lock, the current session can be updated (write operation), and the update operation of other sessions will be blocked.
2.4 Query other tables
2.4.0 Preparation
Re-add a write lock to the Employee table
LOCK TABLE employee WRITE;
2.4.1 Current session
SELECT * FROM department;
2.4.2 Other sessions
2.4.3 Conclusion
After adding a write lock, the current session cannot read other tables, and other sessions can read other tables normally.
3 Conclusion
Write lock, for the current session (Owner), the locked table can be read and updated, but other tables cannot be read;
For other sessions (Other), the locked table cannot be read, let alone updated (will be blocked), but other tables can be read normally;
Write locks are exclusive