测试表DDL
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;
1.READ-UNCOMMITTED(读取未提交内容)级别
READ-UNCOMMITTED隔离级别,当两个事务同时进行时,即使事务没有提交,所做的修改也会对事务内的查询做出影响,这种级别显然很不安全。但是在表对某行进行修改时,会对该行加上行共享锁
client A:
1)select @@TX_ISOLATION;
set session transaction isolation level read uncommitted;
select @@TX_ISOLATION;
select * from user;
2)start transaction;
update user set age=10 where id=1;
clint B:
1)start transaction;
update user set age=10 where id=1;
select * from user;
rollback;
2)update user set age=100 where id=1;//超时
update user set age=100 where id=2;
2. READ-COMMITTED(读取提交内容)
READ-COMMITTED事务隔离级别,只有在事务提交后,才会对另一个事务产生影响,并且在对表进行修改时,会对表数据行加上行共享锁
client A:
1)select @@TX_ISOLATION;
set session transaction isolation level read committed;
select @@TX_ISOLATION;
select * from user;
2)start transaction;
select * from user;
update user set age=100 where id=1;
clint B:
1)start transaction;
update user set age=10 where id=1;
select * from user;
commit;
2)select * from user;
update user set age=101 where id=1;//超时
select * from user;
update user set age=101 where id=2;
3. REPEATABLE-READ(可重读)
REPEATABLE-READ事务隔离级别,当两个事务同时进行时,其中一个事务修改数据对另一个事务不会造成影响,即使修改的事务已经提交也不会对另一个事务造成影响。
在事务中对某条记录修改,会对记录加上行共享锁,直到事务结束才会释放。
client A:
1)select @@TX_ISOLATION;
set session transaction isolation level repeatable read;
select @@TX_ISOLATION;
select * from user;
start transaction;
select * from user;
2)start transaction;
select * from user;
update user set age=100 where id=1;
clint B:
1)start transaction;
update user set age=10 where id=1;
select * from user;
commit;
2)select * from user;
update user set age=101 where id=1;//超时
select * from user;
update user set age=101 where id=2;
select * from user;
start transaction;
update user set age=102 where id=1;//超时
update user set age=101 where id=2;
select * from user;
4.SERIALIZABLE(可串行化、序列化读)
SERIALIZABLE事务隔离级别最严厉,在进行查询时就会对表或行加上共享锁,其他事务对该表将只能进行读操作,而不能进行写操作。
client A:
1)select @@TX_ISOLATION;
set session transaction isolation level serializable;
select @@TX_ISOLATION;
select * from user;
2)start transaction;
select * from user;
commit;
clint B:
1)select * from user;
update user set age=10 where id=1;
1)select * from user;
update user set age=10 where id=1;//报错
不超时的话会自动提交
============================================================================
共享锁:由读表操作加上的锁,加锁后其他用户只能获取该表或行的共享锁,不能获取排它锁,也就是说只能读不能写
排它锁:由写表操作加上的锁,加锁后其他用户不能获取该表或行的任何锁,典型是mysql事务中
start transaction;
select * from user where userId = 1 for update;
执行完这句以后
1)当其他事务想要获取共享锁,比如事务隔离级别为SERIALIZABLE的事务,执行
select * from user;
将会被挂起,因为SERIALIZABLE的select语句需要获取共享锁
2)当其他事务执行
select * from user where userId = 1 for update;
update user set userAge = 100 where userId = 1;
也会被挂起,因为for update会获取这一行数据的排它锁,需要等到前一个事务释放该排它锁才可以继续进行
锁的范围:
行锁: 对某行记录加上锁
表锁: 对整个表加上锁
这样组合起来就有,行级共享锁,表级共享锁,行级排他锁,表级排他锁
原文链接 http://www.cnblogs.com/zemliu/archive/2012/06/17/2552301.html