当前位置:首页 > 通信资讯 > 正文

通常来说C++操作MySQL的时候,往Mysql中插入10000条简单数据,速度非常缓慢,居然要5分钟左右,
而打开事务的话,一秒不到就搞定了!

具体实现代码如下:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 #include <iostream> #include <winsock2.h> #include <string> #include "mysql.h" #pragma comment(lib, "libmysql.lib"); using namespace std; int main() { MYSQL mysql; mysql_init(&mysql); // 初始化 MYSQL *ConnStatus = mysql_real_connect(&mysql,"localhost","root","","sky",3306,0,0); if (ConnStatus == NULL) { // 连接失败 int i = mysql_errno(&mysql); string strError= mysql_error(&mysql); cout <<"Error info: "<<strError<<endl; return 0; } cout<<"Mysql Connected..."<<endl; string strsql; MYSQL_RES *result=NULL; // 数据结果集 // 插入操作 strsql = "insert into t1 values(2,'lyb')"; mysql_query(&mysql,"START TRANSACTION"); // 开启事务, 如果没有开启事务,那么效率会变得非常低下! for (int i=0; i<10000; i++) { mysql_query(&mysql,strsql.c_str()); } mysql_query(&mysql,"COMMIT"); // 提交事务 cout<<"insert end"<<endl; //释放结果集 关闭数据库 mysql_free_result(result); mysql_close(&mysql); mysql_library_end(); return 0; }

总结:

在针对大量数据的插入,更改等操作时,应该开启事务,待一连串的操作结束之后,再提交事务,可提高程序执行效率

如果您对该产品感兴趣,请填写办理(客服微信:xiaoxiongyidong)

为您推荐:

发表评论

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。