mysql事务实例

use test_1;
-- 创建一个账户表
create table my_account(
number char(16) not null unique comment '账户',
name varchar(50) not NULL,
money decimal(10,2) default 0.0 comment '账户余额'
)charset utf8;

-- 插入数据
insert into my_account VALUES
('000000001','张三',1000),
('000000002','李四',2000);

drop table my_account;

select * from my_account;
alter table my_account add id int primary key auto_increment first;
update my_account set money = money -1000 where id=1;

-- 事务(手动操作)
-- 开启事务
start transaction;
-- 李四账户减少
update my_account set money = money -1000 where id=2;
-- 张三账户增加
update my_account set money = money +1000 where id=1;
-- 关闭事务
-- a)提交事务:同步数据库(操作成功)commit
-- b)回滚事务:直接清空日志表(操作失败)rollback
commit;

-- 事务(回滚点)
-- 开启事务
start transaction;
-- 事务1:张三加钱
update my_account set money = money + 10000 where id = 1;
-- 设置回滚点
savepoint sp1;
-- 银行扣税
update my_account set money = money - 10000 * 0.05 where id = 2;-- 错误
-- 回滚到回滚点
rollback to sp1;
-- 继续操作
update my_account set money = money - 10000 * 0.05 where id = 1;
-- 关闭事务
commit;

-- 事务(自动)
-- 关闭自动提交:set autocommit = off/0;
show variables like 'autocommit';
set autocommit = 0;
-- 张三加钱
update my_account set money = money - 10000 where id = 1;
-- 自动提交
set autocommit = 1;

-- 事务的特性:ACID 原子性,一致性,隔离性,持久性

转载于:https://www.cnblogs.com/TianMu/p/7843473.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值