通常來說C++操作MySQL的時候,往Mysql中插入10000條簡單數據,速度非常緩慢,居然要5分鐘左右,
而打開事務的話,一秒不到就搞定了!
具體實現代碼如下:
#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;}
總結:
在針對大量數據的插入,更改等操作時,應該開啟事務,待一連串的操作結束之后,再提交事務,可提高程序執行效率。
新聞熱點
疑難解答