C++操作MySQL大量數據插入效率低下的解決方法


#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;
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM