MySQL事务部分回滚-回滚到指定保存点
我们可以在mysql事务处理过程中定义保存点(SAVEPOINT),然后回滚到指定的保存点前的状态。
定义保存点,以及回滚到指定保存点前状态的语法如下。
-
定义保存点---SAVEPOINT 保存点名;
-
回滚到指定保存点---ROLLBACK TO SAVEPOINT 保存点名:
下面演示将向表user中连续插入3条数据,在插入第2条数据的后面定义一个保存点,最后看看能否回滚到此保存点。
1、查看user表中的数据
-
mysql> select * from user;
-
+-----+----------+-----+------+
-
| mid | name | scx | word |
-
+-----+----------+-----+------+
-
| 1 | zhangsan | 0 | NULL |
-
| 2 | wangwu | 1 | NULL |
-
+-----+----------+-----+------+
-
2 rows in set (0.05 sec)
2、mysql事务开始
-
mysql> BEGIN;
-
Query OK, 0 rows affected (0.00 sec)
3、向表user中插入2条数据
-
mysql> INSERT INTO user VALUES ('3','one','0','');
-
Query OK, 1 row affected (0.08 sec)
-
mysql> INSERT INTO user VALUES ('4,'two','0','');
-
Query OK, 1 row affected (0.00 sec)
-
mysql> select * from user;
-
+-----+----------+-----+------+
-
| mid | name | scx | word |
-
+-----+----------+-----+------+
-
| 1 | zhangsan | 0 | NULL |
-
| 2 | wangwu | 1 | NULL |
-
| 3 | one | 0 | |
-
| 4 | two | 0 | |
-
+-----+----------+-----+------+
-
4 rows in set (0.00 sec)
4、指定保存点,保存点名为test
-
mysql> SAVEPOINT test;
-
Query OK, 0 rows affected (0.00 sec)
5、向表user中插入第3条数据
-
mysql> INSERT INTO user VALUES ('5','three','0','');
-
Query OK, 1 row affected (0.00 sec)
-
mysql> select * from user;
-
+-----+----------+-----+------+
-
| mid | name | scx | word |
-
+-----+----------+-----+------+
-
| 1 | zhangsan | 0 | NULL |
-
| 2 | wangwu | 1 | NULL |
-
| 3 | one | 0 | |
-
| 4 | two | 0 | |
-
| 5 | three | 0 | |
-
+-----+----------+-----+------+
-
5 rows in set (0.02 sec)
6、回滚到保存点test
-
mysql> ROLLBACK TO SAVEPOINT test;
-
Query OK, 0 rows affected (0.31 sec)
-
mysql> select * from user;
-
+-----+----------+-----+------+
-
| mid | name | scx | word |
-
+-----+----------+-----+------+
-
| 1 | zhangsan | 0 | NULL |
-
| 2 | wangwu | 1 | NULL |
-
| 3 | one | 0 | |
-
| 4 | two | 0 | |
-
+-----+----------+-----+------+
-
4 rows in set (0.00 sec)
我们可以看到保存点test以后插入的记录没有显示了,即成功团滚到了定义保存点test前的状态。利用保存点可以实现只提交事务中部分处理的功能。
文章来源网页编程,转载请注明出处:http://uphtm.com/database/192.html