MYSQL—加写锁,加读锁,解锁

时间:2023-03-09 00:12:29
MYSQL—加写锁,加读锁,解锁

链接地址:http://blog.sina.com.cn/s/blog_7fa2bcf50101j1lu.html

表级锁:

加写锁:

         lock   tables   table_name   read;//其他事务只能读,不能加写锁,要等待更新。

加读锁:

        lock   tables   table_name write;//其他事务不能读

解锁:

        unlock  tables;

---------------------------------------------

行级锁:行锁是对索引加锁

id    num

0 100

1 500

5 1000

例1.

事务1:set autocommit = off;

update test set num = 200 where id = 5; 

事务2:select * from test where id=5;可读,得到5 1000;

 

例2.

事务1:set autocommit = off;

update test set num = 200 where id = 5; 

事务2:set autocommit = off;

update test set num = 200 where id = 5;事务2等待事务1提交了才能更新。

例3.

事务1:set autocommit = off;

update test set num = 200 where id = 5; 

事务2:set autocommit = off;

update test set num = 200 where id = 6;事务2不用等待

例4.

事务1:set autocommit = off;

update test set num = 200 where id = 5; 

事务2:insert test (id) value (5);事务2等待,事务1提交后,事务2报错Duplicate entry '5' for key 'PRIMARY'

例5.

事务1:set autocommit = off;

update test set num = 200 where id = 5; 

事务2:insert test (id) value (6);事务2不用等待;

例6.

事务1:insert test (id) value (8); 

事务2:insert test (id) value (9);事务2不用等待;

 

由上可知为什么说行锁是对索引加锁。