mysql create table and insert into via c++ and lmysqlcppconn

发布时间 2023-10-31 01:05:23作者: FredGrit
//create table t1

CREATE TABLE `t1` (
`id` bigint NOT NULL AUTO_INCREMENT,
`author` varchar(40) NOT NULL,
`comment` varchar(40) NOT NULL,
`content` varchar(40) NOT NULL,
`header` varchar(40) NOT NULL,
`isbn` varchar(40) NOT NULL,
`memory` varchar(40) NOT NULL,
`object` varchar(40) NOT NULL,
`result` varchar(40) NOT NULL,
`summary` varchar(40) NOT NULL,
`title` varchar(40) NOT NULL,
`topic` varchar(40) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;


//main.cpp
#include <algorithm>
#include <chrono>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <memory>
#include <mutex>
#include <pqxx/pqxx>
#include <random>
#include <set>
#include <thread>
#include <uuid/uuid.h>
#include <vector>
#include <cppconn/connection.h>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/datatype.h>
#include <cppconn/metadata.h>
#include <cppconn/parameter_metadata.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/sqlstring.h>

template <typename T1, typename T2>
void print_mtx_map(const std::map<T1, T2> _mp, const int &interval);

std::string get_time_now(bool is_exact = true)
{
    std::chrono::time_point<std::chrono::high_resolution_clock> now = std::chrono::high_resolution_clock::now();
    time_t raw_time = std::chrono::high_resolution_clock::to_time_t(now);
    struct tm tm_info = *localtime(&raw_time);
    std::stringstream ss;
    ss << std::put_time(&tm_info, "%Y%m%d%H%M%S");
    if (is_exact)
    {
        std::chrono::seconds seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
        std::chrono::milliseconds mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
        std::chrono::microseconds micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
        std::chrono::nanoseconds nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
        ss << std::setw(3) << std::setfill('0') << (mills.count() - seconds.count() * 1000)
           << std::setw(3) << std::setfill('0') << (micros.count() - mills.count() * 1000)
           << std::setw(3) << std::setfill('0') << (nanos.count() - micros.count() * 1000);
    }
    return ss.str();
}

std::string get_time_span(std::chrono::time_point<std::chrono::high_resolution_clock> _start_time, std::chrono::time_point<std::chrono::high_resolution_clock> _end_time)
{
    std::stringstream ss;
    ss << std::chrono::duration_cast<std::chrono::seconds>(_end_time - _start_time).count() << " seconds,"
       << std::chrono::duration_cast<std::chrono::milliseconds>(_end_time - _start_time).count() << " mills,"
       << std::chrono::duration_cast<std::chrono::microseconds>(_end_time - _start_time).count() << " micros,"
       << std::chrono::duration_cast<std::chrono::nanoseconds>(_end_time - _start_time).count() << " nanos"
       << std::endl;
    return ss.str();
}
 
char uuid_value[37];
uint32_t rand32()
{
    return ((rand() & 0x3) << 30) | ((rand() & 0x7fff) << 15) | (rand() & 0x7fff);
}

char *gen_uuid4()
{
    int n = snprintf(uuid_value, sizeof(uuid_value), "%08x-%04x-%04x-%04x-%04x%08x",
                     rand32(),                       // Generates a 32-bit Hex number
                     rand32() & 0xffff,              // Generates a 16-bit Hex number
                     ((rand32() & 0x0fff) | 0x4000), // Generates a 16-bit Hex number of the form 4xxx (4 indicates the UUID version)
                     (rand32() & 0x3fff) + 0x8000,   // Generates a 16-bit Hex number in the range [0x8000, 0xbfff]
                     rand32() & 0xffff, rand32());   // Generates a 48-bit Hex number
    // return n >= 0 && n < len;             // Success only when snprintf result is a positive number and the provided buffer was large enough.
    return uuid_value;
}
 
void insert_into_mysql_table()
{     
    sql::Driver *driver = get_driver_instance(); 
    sql::Connection *conn = driver->connect("localhost", "username_value", "password_value");
    conn->setSchema("db");
    std::cout << std::boolalpha << conn->isValid() << std::endl;
    sql::Statement *stmt = conn->createStatement();
    std::string sql_str; 
    std::stringstream ss;
    srand(time(NULL));
    std::uint64_t num = 0;

    for (int loop = 0; loop < 1000; loop++)
    {
        ss = std::stringstream();
        ss << "insert into t1(author,comment,content,header,isbn,memory,object,result,summary,title,topic) values ";
        for (int i = 0; i < 1000000; i++)
        {
            ss << "('" << gen_uuid4() << "','" << gen_uuid4() << "','" << gen_uuid4() << "','" << gen_uuid4() << "','"
               << gen_uuid4() << "','" << gen_uuid4() << "','" << gen_uuid4() << "','" << gen_uuid4() << "','"
               << gen_uuid4() << "','" << gen_uuid4() << "','" << gen_uuid4() << "'),";
            ++num;
        }
        sql_str = ss.str();
        int last_comma_idx = sql_str.find_last_of(",");
        sql_str = sql_str.substr(0, last_comma_idx);
        stmt->execute(sql_str);
        std::cout << get_time_now() << ",num:" << num <<",loop:"<<loop+1<< " thread id:" << std::this_thread::get_id() << std::endl;
    }
    conn->close();
    std::cout << get_time_now() << ",finished thread id:" << std::this_thread::get_id() << ",line " << __LINE__ << " of " << __FUNCTION__ << std::endl;
}

int main(int args, char **argv)
{ 
    insert_into_mysql_table();
    std::cout << get_time_now() << ",finished in " << __LINE__ << " of " << __FUNCTION__ << std::endl;
}

 

Compile

g++-13 -std=c++23 -I. main.cpp -luuid -lpthread -lmysqlcppconn -o h1;

 

Run

nohup ./h1 >>insert.log |tail -f insert.log

 

show columns from db.t1;


select * from t1 order by id desc limit 1;