通常來說C++操作MySQL的時候,往Mysql中插入10000條簡單數(shù)據(jù),速度非常緩慢,居然要5分鐘左右,
而打開事務(wù)的話,一秒不到就搞定了!
具體實現(xiàn)代碼如下:
#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; // 數(shù)據(jù)結(jié)果集 // 插入操作 strsql = "insert into t1 values(2,'lyb')"; mysql_query(&mysql,"START TRANSACTION"); // 開啟事務(wù), 如果沒有開啟事務(wù),那么效率會變得非常低下! for (int i=0; i<10000; i++) { mysql_query(&mysql,strsql.c_str()); } mysql_query(&mysql,"COMMIT"); // 提交事務(wù) cout<<"insert end"<<endl; //釋放結(jié)果集 關(guān)閉數(shù)據(jù)庫 mysql_free_result(result); mysql_close(&mysql); mysql_library_end(); return 0;}
總結(jié):
在針對大量數(shù)據(jù)的插入,更改等操作時,應(yīng)該開啟事務(wù),待一連串的操作結(jié)束之后,再提交事務(wù),可提高程序執(zhí)行效率。
新聞熱點
疑難解答