MySQL数据库的事务transaction

2019-11-28  本文已影响0人  BJ000

事务操作分两种:自动事务(默认)、手动事务

手动事务的操作流程

开启事务:start transaction;

进行事务操作

关闭事务

提交事务:commit; 同步数据表,表示操作成功

回滚事务:rollback; 直接清空日志表,表示操作失败

事务操作原理:事务开启之后,所有的操作都会临时保存到事务日志,而事务日志只有在得到commit命令才会同步到数据表,其他任何情况都会清空,比如rollback、断电、断开连接

回滚点

设置回滚点语法:savepoint 回滚点名字;

回到回滚点语法:rollback to 回滚点名字;

自动事务处理

show variables like 'autocommit';

关闭自动提交:set autocommit=off/0;

事务的四大特性:ACID

A:Atomic,原子性

C:Consistency,一致性

I:Isolation,隔离性

D:Durability,持久性

锁机制

代码:

-- 创建一个账户

create table my_account(

idint primary key auto_increment,

number char (16)not null unique

comment'账户',

name varchar (20)not null ,

moneydecimal (10,2)default 0.0

comment'账户余额'

)charset utf8;

-- 插入数据

insert into my_accountvalues

(null,'1234567890000000','张三','1000'),

(null,'1234567890000001','李四','2000');

-- 张三转账1000元给李四

update my_accountset money=money-1000 where id=1;

-- 事物安全

-- 开启事物

starttransaction;

-- 事物的操作;1,李四账户减少钱

update my_accountset money=money-1000

where id=2;

-- 事物操作;2,张三账户增加

update my_accountset money=money+1000

where id=1;

-- 提交事物

commit;

-- 回滚点操作

-- 开启事物加钱

starttransaction ;

-- 事物处理1;张三发工资了,

update my_accountset money=money+10000

where id=1;

-- 设置回滚点

savepoint sp1;

-- 银行扣税

update my_accountset money=money-10000*0.05 where id=2;  -- 错误

-- 回滚到回滚点

rollback to sp1;

-- 继续操作  银行扣税

update my_accountset money=money-10000*0.05 where id=1;

-- 查看结果

select * from my_account;

-- 提交结果

commit;

-- 显示系统变量autocommit(模糊查询)

show variableslike 'autocommit';

-- 关闭事物自动提交

set autocommit=0;--off/0

-- 给李四发工资

update my_accountset money=money+10000 where id=2;

commit;

-- 银行扣税

update my_accountset money=money-10000*0.05 where id=2;

-- 事物的隔离性

starttransaction;

-- 给张三返税,返500块钱

update my_accountset money=money+500

where id=1;

-- 另外窗口开启事物

        starttransaction;

-- 李四淘宝花了500

        update my_accountset money=money-500 where id=2;

select * from my_account;

commit;

select * from my_account;

-- 回到张三窗口;事物回滚

rollback;

select * from my_account;  -- 两边一致

-- 锁机制

starttransaction;

-- 使用非索引字段(name),行锁自动上升为表锁

update my_accountset money=money+500

where name='张三';

update my_accountset money=money+1000 where id=2;

上一篇 下一篇

猜你喜欢

热点阅读