数据库
首页 > 数据库> > Mysqlclient insert into table in bulk

Mysqlclient insert into table in bulk

作者:互联网

1.h1.cpp

#include <chrono>
#include <iostream>
#include <mysql/mysql.h>
#include <sstream>
#include <string.h>
#include <uuid/uuid.h>

using namespace std;

static char *uuidValue = (char *)malloc(40);

void mysqlClientDemo();
void mysqlClientInsert2();
void insertBulk3(int loops);

char *getUuid()
{
    uuid_t newUUID;
    uuid_generate(newUUID);
    uuid_unparse(newUUID, uuidValue);
    return uuidValue;
}

int main(int args, char **argv)
{
    insertBulk3(atoi(argv[1]));
}

void insertBulk3(int loops)
{
    try
    {
        MYSQL *conn, mysql;
        int state;

        mysql_init(&mysql);
        conn = mysql_real_connect(&mysql, "localhost", "root", "Root0001!", "myDB", 0, 0, 0);

        if (conn == NULL)
        {
            cout << mysql_error(&mysql) << endl;
            return;
        }

        stringstream ss;
        int64_t num = 0;
        int repeatedTimes = 1000000;
        chrono::time_point<chrono::system_clock> startTime;
        chrono::time_point<chrono::system_clock> endTime;
        for (int i = 0; i < loops; i++)
        {
            startTime = chrono::system_clock::now();
            ss = stringstream();
            ss << "insert into mt(BookId,BookName,BookTitle) values ";
            for (int j = 0; j < repeatedTimes; j++)
            {

                ss << "(" << ++num << ",'" << getUuid() << "','" << getUuid() << "')," << endl;
            }

            string str = ss.str();
            int lastIndex = str.find_last_of(",");
            str = str.erase(lastIndex);
            state = mysql_query(conn, str.c_str());
            endTime = chrono::system_clock::now();
            if (state != 0)
            {
                cout << "Num=" << num << " failed!" << endl;
                return;
            }
            cout << "Loops=" << i + 1 << ",Num=" << num << " succeeded!,time cost:"
                 << chrono::duration_cast<chrono::seconds>(endTime - startTime).count() << " seconds,"
                 << chrono::duration_cast<chrono::milliseconds>(endTime - startTime).count() << " milliseconds,"
                 << chrono::duration_cast<chrono::microseconds>(endTime - startTime).count() << " microseconds,"
                 << chrono::duration_cast<chrono::nanoseconds>(endTime - startTime).count() << " nanoseconds!!!" << endl
                 << endl;
        }
    }
    catch (const std::exception &e)
    {
        std::cerr << e.what() << '\n';
    }
}

 

2.Compile

g++ -g -std=c++2a -I. -Wall -I/usr/include/mysql/ *.cpp -o h1 -L/usr/lib -lmysqlclient -luuid;

 

3.Execute

./h1 100;

 

 

 

标签:insert,char,endTime,int,into,bulk,startTime,mysql,include
来源: https://www.cnblogs.com/Fred1987/p/16275307.html