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;
	}
相关推荐
Mr_hwt_1234 分钟前
基于MyCat 中间件实现mysql集群读写分离与从库负载均衡教程(详细案例教程)
数据库·mysql·中间件·mysql集群
酷ku的森1 小时前
Redis中的Zset数据类型
数据库·redis·缓存
zhong liu bin1 小时前
MySQL数据库面试题整理
数据结构·数据库·mysql
luckys.one6 小时前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
言之。7 小时前
Django中的软删除
数据库·django·sqlite
阿里嘎多哈基米8 小时前
SQL 层面行转列
数据库·sql·状态模式·mapper·行转列
抠脚学代码9 小时前
Ubuntu Qt x64平台搭建 arm64 编译套件
数据库·qt·ubuntu
jakeswang9 小时前
全解MySQL之死锁问题分析、事务隔离与锁机制的底层原理剖析
数据库·mysql
Heliotrope_Sun9 小时前
Redis
数据库·redis·缓存
一成码农9 小时前
MySQL问题7
数据库·mysql