Experiment with Data Locks in MySQL

Q

How To Experiment Data Locks in MySQL?

✍: FYIcenter.com

A

If you want to have some experience with data locks, you can create two windows running two mysql transactions in two sessions. In session 1, you can run a UPDATE statement with REPEATABLE READ transaction isolation level to create an exclusive lock. Before committing session 1, switch to session 2, and run a UPDATE statements on the same row as session 1. The UPDATE statement will be put into wait status because of the data lock. Follow the tutorial exercise below to experience yourself:

(session 1)

>\mysql\bin\mysql -u dev -piyf fyi

mysql> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Query OK, 0 rows affected (0.00 sec)

mysql> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT * FROM fyi_links;
+-----+---------------+-------+--------+--------------------
| id  | url           | notes | counts | created           
+-----+---------------+-------+--------+--------------------
| 101 | fyicenter.com | Good  |    999 | 2006-07-01 20:34:10
| 110 | centerfyi.com | Wrong |      0 | 2006-07-01 20:34:12
+-----+---------------+-------+--------+--------------------
2 rows in set (0.00 sec)

mysql> UPDATE fyi_links SET url='FYICENTER.COM' 
   WHERE id=101;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

(Exclusive lock (X) placed on row id=101)

Switch to session 2:

(session 2)

>\mysql\bin\mysql -u dev -piyf fyi

mysql> SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
Query OK, 0 rows affected (0.00 sec)

mysql> START TRANSACTION;
Query OK, 0 rows affected (0.00 sec)

mysql> UPDATE fyi_links SET notes='Best' where id=101;

(Blocked to wait for exclusive lock (X) on row id=101)

Switch to back session 1:

(session 1)

mysql> COMMIT;
Query OK, 0 rows affected (0.05 sec)

(Exclusive lock (X) on row id=101 released)

Switch to session 2:

(session 2)

Query OK, 1 row affected (11.80 sec)
Rows matched: 1  Changed: 1  Warnings: 0

(Got permission to update row id=101)

 

Transaction Waiting for a Data Lock in MySQL

What Is a Data Lock in MySQL

Transaction Management: Commit or Rollback in MySQL

⇑⇑ MySQL Database Tutorials

2017-04-28, 1547🔥, 0💬