Home > Database > Mysql Tutorial > body text

MySQL事务部分回滚

WBOY
Release: 2016-06-07 15:52:21
Original
1295 people have browsed it

我们可以在mysql事务处理过程中定义保存点(SAVEPOINT),然后回滚到指定的保存点前的状态。 定义保存点,以及回滚到指定保存点前状态的语法如下。 定义保存点---SAVEPOINT 保存点名; 回滚到指定保存点---ROLLBACK TO SAVEPOINT 保存点名: 下面演示将向表user

我们可以在mysql事务处理过程中定义保存点(SAVEPOINT),然后回滚到指定的保存点前的状态。

定义保存点,以及回滚到指定保存点前状态的语法如下。

  1. 定义保存点---SAVEPOINT 保存点名;
  2. 回滚到指定保存点---ROLLBACK TO SAVEPOINT 保存点名:

下面演示将向表user中连续插入3条数据,在插入第2条数据的后面定义一个保存点,最后看看能否回滚到此保存点。

1、查看user表中的数据

  1. mysql> select * from user;
  2. +-----+----------+-----+------+
  3. | mid | name | scx | word |
  4. +-----+----------+-----+------+
  5. | 1 | zhangsan | 0 | NULL |
  6. | 2 | wangwu    | 1 | NULL |
  7. +-----+----------+-----+------+
  8. 2 rows in set (0.05 sec)

2、mysql事务开始

  1. mysql> BEGIN;
  2. Query OK, 0 rows affected (0.00 sec)

3、向表user中插入2条数据

  1. mysql> INSERT INTO user VALUES ('3','one','0','');
  2. Query OK, 1 row affected (0.08 sec)
  3. mysql> INSERT INTO user VALUES ('4,'two','0','');
  4. Query OK, 1 row affected (0.00 sec)
  5. mysql> select * from user;
  6. +-----+----------+-----+------+
  7. | mid | name | scx | word |
  8. +-----+----------+-----+------+
  9. | 1 | zhangsan | 0 | NULL |
  10. | 2 | wangwu    | 1 | NULL |
  11. | 3 | one            | 0 | |
  12. | 4 | two             | 0 | |
  13. +-----+----------+-----+------+
  14. 4 rows in set (0.00 sec)

4、指定保存点,保存点名为test

  1. mysql> SAVEPOINT test;
  2. Query OK, 0 rows affected (0.00 sec)

5、向表user中插入第3条数据

  1. mysql> INSERT INTO user VALUES ('5','three','0','');
  2. Query OK, 1 row affected (0.00 sec)
  3. mysql> select * from user;
  4. +-----+----------+-----+------+
  5. | mid | name | scx | word |
  6. +-----+----------+-----+------+
  7. | 1 | zhangsan | 0 | NULL |
  8. | 2 | wangwu | 1 | NULL |
  9. | 3 | one | 0 | |
  10. | 4 | two | 0 | |
  11. | 5 | three | 0 | |
  12. +-----+----------+-----+------+
  13. 5 rows in set (0.02 sec)

6、回滚到保存点test

  1. mysql> ROLLBACK TO SAVEPOINT test;
  2. Query OK, 0 rows affected (0.31 sec)
  3. mysql> select * from user;
  4. +-----+----------+-----+------+
  5. | mid | name | scx | word |
  6. +-----+----------+-----+------+
  7. | 1 | zhangsan | 0 | NULL |
  8. | 2 | wangwu    | 1 | NULL |
  9. | 3 | one            | 0 | |
  10. | 4 | two            | 0 | |
  11. +-----+----------+-----+------+
  12. 4 rows in set (0.00 sec)

我们可以看到保存点test以后插入的记录没有显示了,即成功团滚到了定义保存点test前的状态。利用保存点可以实现只提交事务中部分处理的功能。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template