1.设置和验证MySQL数据库的隔离级别
- 登录数据库
mysql -u root - p - 新建用户,各启动一个事物,用于同时操作数据库表中数据
create user tom identified by 'tom';
然后同时再用该用户启动MySQL。这样就能通过使用两个事物操作数据库进行验证了
mysql -u tom -p - 新建的tom用户是没有权限对其他数据库进行操作的,因此要赋予权限。通过系统用户对该tom用户赋予权限:
grant select,insert,update,delete on test.* to tom@localhost identified by 'tom';
注意:MySQL8.0不支持这种写法了,需要把identified by 'tom'去掉。前面默认创建的主机是%,即任意主机,因此要把localhost改成'%'; - 两个用户分别
use test;
下面是我创建的test数据库中的user_table表:
![image]()
root-->select * from user_table where user = 'CC';
tom-->select * from user_table where user = 'CC';
默认情况下,这两个DML操作都自动提交了。因此这两个语句事实上是两个事物。 - 让其执行完DML之后,不自动提交
set autocommit = false; - 先查看其隔离级别
select @@tx_isolation;
MySQL8.0后是select @@transaction_isolation;-->REPEATABLE-READ;
7.验证隔离级别
root-->select * from user_table where user = 'cc';
tom-->update user_table set balance = 3000 where user = 'cc';
tom-->select * from user_table where user = 'cc';-->3000
root-->select * from user_table where user = 'cc';-->2000
因为此时两者都没有提交,这里就验证了避免脏读的问题;
tom-->commit;
root-->select * from user_table where user = 'cc';-->2000
这里tom提交,说明数据库已经改了,但是root查询到的仍然是2000,验证了避免不可重复读的问题;
若想root读到3000,只需root提交之后,再次查询即可。(提交意味着当前事物已经结束了) - 修改隔离级别
设置数据库系统的全局的隔离级别
set global transaction isolation level read committed;
然后需要把当前连接断掉,重新进入MySQL才能显示已修改的隔离级别。
9.再次执行5、6、7中代码进行验证既可。
10.再次修改隔离级别为read uncommitted进行验证。
滴水穿石、燕子衔泥,点点滴滴都是添补


浙公网安备 33010602011771号