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;
g++ -g -std=c++2a -I. -I/usr/include/lib *.cpp -o h1 -lmysqlclient -luuid;
g++ -g -std=c++2a -I. *.cpp -o h1 -lmysqlclient -luuid;
3.Execute
time ./h1 100;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现