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;
	}
相关推荐
大春儿的试验田几秒前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
Ein hübscher Kerl.32 分钟前
虚拟机上安装 MariaDB 及依赖包
数据库·mariadb
长征coder1 小时前
AWS MySQL 读写分离配置指南
mysql·云计算·aws
醇醛酸醚酮酯1 小时前
Qt项目锻炼——TODO清单(二)
开发语言·数据库·qt
ladymorgana1 小时前
【docker】修改 MySQL 密码后 Navicat 仍能用原密码连接
mysql·adb·docker
PanZonghui1 小时前
Centos项目部署之安装数据库MySQL8
linux·后端·mysql
GreatSQL社区2 小时前
用systemd管理GreatSQL服务详解
数据库·mysql·greatsql
掘根2 小时前
【MySQL进阶】错误日志,二进制日志,mysql系统库
数据库·mysql
weixin_438335402 小时前
基础知识:mysql-connector-j依赖
数据库·mysql
小明铭同学2 小时前
MySQL 八股文【持续更新ing】
数据库·mysql