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;
	}
相关推荐
nVisual2 小时前
机柜PDU安装位置与空间建模方案
大数据·网络·数据库·信息可视化·数据中心基础设施管理
weixin_6682 小时前
Cursor-superpowers插件用法
数据库·人工智能
NWU_白杨2 小时前
三种常用的数据存储技术
数据库·redis·mysql·sqlite
蓝创工坊Blue Foundry2 小时前
图片文字提取到 Excel:批量任务如何先定义要交付的字段
运维·服务器·开发语言·数据库·自动化·ocr·excel
一嘴一个橘子3 小时前
MySqL 的 B+树、 叶子节点、非叶子节点
mysql
麦聪聊数据3 小时前
企业数据市场建设(三):API 化服务封装,让数据开箱即用、避免重复开发
数据库
脱胎换骨-军哥3 小时前
C++数据库存储引擎内核开发:B+树索引与MVCC并发控制的完整实现
数据库·c++·b树
麦聪聊数据3 小时前
企业数据市场建设(四):流程闭环与价值运营,让数据市场真正转起来
运维·数据库
正儿八经的少年3 小时前
redis 的大 key 和热 key 详解
数据库·redis·缓存
AI砖家3 小时前
多智能体系统实战:架构设计、数据库表设计与 Skill 体系
数据库·多智能体·skill·agent架构设计·agengt