操作语句
开启事务
begin;#声明新事务
start transaction;#声明新事务
提交事务
commit;#提交当前事务
commit work;#提交当前事务
提交事务,对数据库进行所有修改都将变为永久性的
回滚
rollback;#回滚当前事务
rollback work;#回滚当前事务
savepoint s1;#在事务内设标记点s1,作用为分段回滚
rollback to [savepoint] s1;#将事务回滚到事务中的某个标记点
开启或者关闭自动提交
set autocommit=1;#开启自动提交,mysql默认为1
set autocommit=0;#关闭自动提交
show variables like 'autocommit';#查看mysql当前commit值
如果没有开启自动提交,那么当前会话连接的mysql所有操作都会在你输入rollback(回滚)或者commit(提交事务)时,才算事务结束。当前事务结束前新的mysql连接时无法读取到任何会话的操作结果。
如果开启了自动提交,那么mysql会将每一个sql语句都当做一个独立的事务,即msyql会帮助你在每一个sql语句后打出commit。
模拟实现多用户
use 数据库
show session variables like '%isolation%';
create table account (name varchar(32),id int primary key, age int ,money float);
INSERT into account VALUE("张三",1,20,1000);
INSERT into account VALUE("李四",2,30,2000);
INSERT into account VALUE("王五",3,40,3000);
INSERT into account VALUE("李六",4,50,4000);
#使用远程连接工具在开用户b
set session transaction isolation level Read Uncommitted;#设置读未提交
show session variables like '%isolation%';#查看设置
脏读
##a操作
begin;
update account set money=money/20 where id=2;
##不提交
##b操作
select * from account;
得到结果:

不可重复读
##a操作
begin;
select * from account;
##b操作结束后a:
select * from account where id=2;
##b操作
update account set money=money*100 where id=2;
得到结果:

幻读
##a操作
begin;
update account set age=30;
##b操作结束后a:
select * from account;
##b操作
begin;
insert account value ('dz',5,15,15);
得到结果:

丢失更新
##a操作
BEGIN;
SELECT * from account;
##B先修改数据,提交事务
UPDATE account set money=money/100 where id=2;
SELECT * from account;
##b操作
BEGIN;
SELECT * from account;
UPDATE account set money=money*80 where id=2;
COMMIT;
SELECT * from account;
得到结果:
