MySQL事务--6个步骤

第一步:1、开始事务

复制代码
START TRANSACTION

第二步:取消手动提交事务

复制代码
set autocommit=0

第三步:插入sql语句

复制代码
sql语句

第四步:回滚,ROLLBACK

出错 回滚 ROLLBACK ( MYISAM不支持,引擎记得修改为InnoDB)

复制代码
ROLLBACK

第五步:提交

复制代码
COMMIT

第六步:恢复自动提交

复制代码
set autocommit=1

//事务
	// 1、开始事务
	//START TRANSACTION;

	sql = "START TRANSACTION";

	re = mysql_query(&mysql, sql.c_str());
	if (re != 0)
	{
		cout << "failed mysql_error" << mysql_error(&mysql) << endl;
	}


	//2、手动提交事务
	//set auocommit=0;
	sql = "set autocommit=0";

	re = mysql_query(&mysql, sql.c_str());
	if (re != 0)
	{
		cout << "failed mysql_error" << mysql_error(&mysql) << endl;
	}

	//3、sql语句
	//插入三条语句,回滚
	for (int i = 0;i < 3;i++)
	{
		sql = "insert into t_vedio (name) values ('test three!')";

		re = mysql_query(&mysql, sql.c_str());
		if (re != 0)
		{
			cout << "failed mysql_error" << mysql_error(&mysql) << endl;
		}
	}

	//4、出错回滚 ROLLBACK  MYISAM不支持

	sql = "ROLLBACK";
	re = mysql_query(&mysql, sql.c_str());
	if (re != 0)
	{
		cout << "failed mysql_error" << mysql_error(&mysql) << endl;
	}
	//count=0
	//插入三条语句,回滚
	for (int i = 0;i <100;i++)
	{
		sql = "insert into t_vedio (name) values ('test three!')";

		re = mysql_query(&mysql, sql.c_str());
		if (re != 0)
		{
			cout << "failed mysql_error" << mysql_error(&mysql) << endl;
		}
	}


	//5、COMMIT
	sql = "COMMIT";
	re = mysql_query(&mysql, sql.c_str());
	if (re != 0)
	{
		cout << "failed mysql_error" << mysql_error(&mysql) << endl;
	}


	//6、恢复自动提交
	//set auocommit=1;
	sql = "set autocommit=1";
	re = mysql_query(&mysql, sql.c_str());
	if (re != 0)
	{
		cout << "failed mysql_error" << mysql_error(&mysql) << endl;
	}
相关推荐
hoho_12几秒前
docker中升级mysql到最新版本
mysql·docker·容器
后台模板学习2 分钟前
学习的心态高频面试题
java·数据库·学习
redreamSo21 分钟前
想给产品加一个 AI 搜索,是上向量数据库还是用 MongoDB 就够了?
数据库·人工智能·mongodb
Linux-lucky1 小时前
36-Linux学习之旅之MySQL主从复制
linux·运维·学习·mysql·ubuntu
APItesterCris2 小时前
告别人工盯品!借助 Open‑Claw 快速搭建电商商品全自动监控与数据分析系统(完整实操代码)
java·大数据·前端·数据库
SKH.2 小时前
网络(5)数据库
jvm·数据库
kyrie_sakura2 小时前
MySQL数据库学习笔记3--关联(联合)查询
数据库·学习·mysql
陈皮波比茶3 小时前
计算机二级MySQL笔记
java·数据库
行业研究员3 小时前
腾讯云数据库 PostgreSQL 让相关子查询跑上多核
数据库·postgresql·腾讯云