C++ operation MySQL large data insertion inefficient solution
- 2020-04-02 02:29:10
- OfStack
Generally speaking, when C++ operates MySQL, it is very slow to insert 10,000 pieces of simple data into MySQL. It takes about 5 minutes.
And open the transaction, less than a second to be done!
The specific implementation code is as follows:
#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); //Initialize the
MYSQL *ConnStatus = mysql_real_connect(&mysql,"localhost","root","","sky",3306,0,0);
if (ConnStatus == NULL)
{
//The connection fails
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; //Data result set
//The insert
strsql = "insert into t1 values(2,'lyb')";
mysql_query(&mysql,"START TRANSACTION"); //Open transactions, if not open transactions, then the efficiency is very low!
for (int i=0; i<10000; i++)
{
mysql_query(&mysql,strsql.c_str());
}
mysql_query(&mysql,"COMMIT"); //Commit the transaction
cout<<"insert end"<<endl;
//Releasing the result set closes the database
mysql_free_result(result);
mysql_close(&mysql);
mysql_library_end();
return 0;
}
Conclusion:
In the case of a large number of data inserts, changes, etc., the transaction should be started, after the completion of a series of operations, then commit the transaction, can improve the execution efficiency of the program.