MYSQL事务操作
作者:xlnxin发布时间:2025-02-10分类:编程知识浏览:81
导读:事务是数据库管理系统中的一个重要概念,它用于保证数据库操作的完整性和一致性。事务可以确保一组操作要么全部成功,要么全部失败,避免了部分成功部分失败的情况,从而保持数据的一致性。--...
事务是数据库管理系统中的一个重要概念,它用于保证数据库操作的完整性和一致性。事务可以确保一组操作要么全部成功,要么全部失败,避免了部分成功部分失败的情况,从而保持数据的一致性。
-- ---------------------------------------- 事务操作 ------------------------------------- create table account ( id int primary key AUTO_INCREMENT comment ' ID', name varchar(10) comment ' 姓名 ', money double(10, 2) comment ' 余额 ' ) comment ' 账户表 '; insert into account(name, money) VALUES (' 张三 ', 2000), (' 李四 ', 2000); -- 恢复数据 update account set money = 2000 where name = ' 张三 ' or name = ' 李四 '; select @@autocommit; set @@autocommit = 1; -- 设置手动提交 -- 转账操作 -- 正常情况 -- 1 . 查询张三余额 select * from account where name = ' 张三 ' ; -- 2 . 张三的余额减少 1000 update account set money = money - 1000 where name = ' 张三 ' ; -- 3 . 李四的余额增加 1000 update account set money = money + 1000 where name = ' 李四 ' ; -- 异常情况 -- 1 . 查询张三余额 select * from account where name = ' 张三 ' ; -- 2 . 张三的余额减少 1000 update account set money = money - 1000 where name = ' 张三 ' ; -- 出错了 . . . . -- 3 . 李四的余额增加 1000 update account set money = money + 1000 where name = ' 李四 ' ; -- 提交事务 commit; -- 回滚事务(出现异常就操作) rollback; -- 方式二 -- 转账操作 start transaction; -- 异常情况 -- 1 . 查询张三余额 select * from account where name = ' 张三 ' ; -- 2 . 张三的余额减少 1000 update account set money = money - 1000 where name = ' 张三 ' ; -- 出错了 . . . . -- 3 . 李四的余额增加 1000 update account set money = money + 1000 where name = ' 李四 ' ; -- 提交事务 commit; -- 回滚事务 rollback; -- 事务隔离级别 -- 查看事务隔离级别 select @@transaction_isolation; -- 设置事务隔离级别 set session transaction isolation level read uncommitted; set session transaction isolation level repeatable read;
- 编程知识排行
- 最近发表