写在前面
本文看下MySQL的savepoint相关内容。
1:什么是savepoint
savepoint是事务中一个概念,允许在事务执行的过程中暂存事务执行到当前所产生的修改,这样当我们需要回滚事务时就可以选择回滚到某个保存点,而不用回滚整个事务。语法格式如下:
生成一个savepoint:
SAVEPOINT the_savepoint_name
回滚事务到某个savepoint:
ROLLBACK [WORK] TO [SAVEPOINT] the_savepoint_name
释放暂存点:
RELEASE SAVEPOINT the_savepoint_name
2:实例
如下表:
java
mysql> select * from words where id in (1,2);
+----+------+
| id | word |
+----+------+
| 1 | aaaa |
| 2 | aaab |
+----+------+
2 rows in set (0.00 sec)
接下来我们分别对id为1,2的word都拼加字符串hi
,并分别生成保存点,最终回滚到id为1的修改保存点,并提交事务,因此最终只有id=1的word会追加hi
成功,操作如下:
mysql> start transaction with consistent snapshot;
Query OK, 0 rows affected (0.00 sec)
mysql> update words set word=concat(word,'hi') where id=1;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> savepoint sp_id_1; // 生成第一个暂存点
Query OK, 0 rows affected (0.00 sec)
mysql> update words set word=concat(word,'hi') where id=2;
Query OK, 1 row affected (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> savepoint sp_id_2; // 生成第二个暂存点
Query OK, 0 rows affected (0.00 sec)
mysql> rollback to savepoint sp_id_1; // 回滚到第一个暂存点,则第一个暂存点之后的所有修改都会被回滚,但第一个暂存点之前的修改回被保留
Query OK, 0 rows affected (0.00 sec)
mysql> commit;
Query OK, 0 rows affected (0.06 sec)
mysql> select * from words where id in (1,2);
+----+--------+
| id | word |
+----+--------+
| 1 | aaaahi |
| 2 | aaab |
+----+--------+
2 rows in set (0.00 sec)
可以看到最终只要id=1的word值成功追加了hi
。