MySQL的savepoint分析

写在前面

本文看下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

写在后面

参考文章列表

MySQL 基础 ------------ SAVEPOINT 的应用

相关推荐
wertyuytrewm21 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
koping_wu21 小时前
常用中间件面试汇总:Mysql、Mq、Redis、操作系统、Nacos、Es、Mybatis
mysql·中间件·面试
mldlds21 小时前
MySQL四种备份表的方式
mysql·adb·oracle
一叶飘零_sweeeet1 天前
MySQL高可用生产落地全解:主从同步、MGR集群、读写分离从原理到实战
数据库·mysql·架构·mysql高可用
qqty12171 天前
MySQL Workbench菜单汉化为中文
android·数据库·mysql
2401_895521341 天前
MySQL中between and的基本用法
android·数据库·mysql
2301_810160951 天前
使用Flask快速搭建轻量级Web应用
jvm·数据库·python
wenlonglanying1 天前
MySQL事件功能简介
数据库·mysql
l1t1 天前
DeepSeek总结的用 C# 构建 DuckDB 插件说明
前端·数据库·c#·插件·duckdb
czlczl200209251 天前
Redis过期删除策略
数据库·redis·缓存