美文网首页
MySQL数据库事务【transaction】

MySQL数据库事务【transaction】

作者: 泡泡龙吐泡泡 | 来源:发表于2018-09-18 20:28 被阅读42次

    1. 引入

    1. 事务是一个不可分割的执行单元
    2. 事务作为一个整体要么一起执行,要么一起回滚

    插入测试数据:

    mysql> select * from stu where ch=(select ch from stu where stusex='女' order by ch desc limit 1);
    +--------+---------+--------+--------+---------+------------+------+------+
    | stuNo  | stuName | stuSex | stuAge | stuSeat | stuAddress | ch   | math |
    +--------+---------+--------+--------+---------+------------+------+------+
    | s25321 | Tabm    | 女     |     23 |       9 | 河北       |   88 |   77 |
    +--------+---------+--------+--------+---------+------------+------+------+
    1 row in set (0.00 sec)
    
    mysql> create table bank(
        -> carid char(4) primary key,
        -> money int
        -> );
    Query OK, 0 rows affected (0.02 sec)
    
    mysql> insert into bank values ('1001',1000),('1002',100);
    Query OK, 2 rows affected (0.01 sec)
    Records: 2  Duplicates: 0  Warnings: 0
    

    2. 事务操作

    开启事务:start transaction 或者 begin [work]
    提交事务:commit
    回滚事务:rollback
    

    例题:

    mysql>  start transaction;
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> insert into bank values ('1003',1000);
    Query OK, 1 row affected (0.00 sec)
    
    mysql> savepoint aa;    # 设置回滚点 aa
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> insert into bank values ('1004',500);
    Query OK, 1 row affected (0.00 sec)
     
    mysql> savepoint bb;   # 设置回滚点bb
    Query OK, 0 rows affected (0.00 sec)
     
    mysql> rollback to aa;    # 回滚到aa点
    Query OK, 0 rows affected (0.00 sec)
    
    mysql> commit;    # 提交事务
    
    mysql> select * from bank ;
    +--------+-------+
    | cardid | money |
    +--------+-------+
    | 1001   |   800 |
    | 1002   |   200 |
    | 1003   |  1000 |
    +--------+-------+
    

    3. 事务的特性(ACID)

    1. 原子性(Atomicity):事务是一个整体,不可以再分,要么一起执行,要么一起不执行。
    2. 一致性(Consistency):事务完成时,数据必须处于一致的状态。
    3. 隔离性(Isolation):每个事务都是相互隔离的
    4. 永久性(Durability):事务完成后,对数据的修改是永久性的。

    相关文章

      网友评论

          本文标题:MySQL数据库事务【transaction】

          本文链接:https://www.haomeiwen.com/subject/rzkrnftx.html