標籤:action 操作 track names free 資料 tran span star
往 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;}
總結:
在大量資料的插入,更改等操作時,應該開啟事務。等一連串的操作結束之後,再提交事務。可提高程式運行效率
解決 C++ 操作 MySQL 大量資料插入效率低下問題