首页 > 数据库 >linux mysql libmysqlcppconn select,update mysql

linux mysql libmysqlcppconn select,update mysql

时间:2023-12-11 18:14:38浏览次数:47  
标签:std now chrono ss libmysqlcppconn mysql update time include

#include <chrono>
#include <cstring>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iomanip>
#include <iostream>
#include <memory>
#include <mutex>
#include <queue>
#include <random>
#include <sstream>
#include <thread>
#include <vector>
#include <cppconn/driver.h>
#include <cppconn/connection.h>
#include <cppconn/metadata.h>
#include <cppconn/parameter_metadata.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/resultset_metadata.h>
#include <cppconn/statement.h>

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)
    {
        auto seconds = std::chrono::duration_cast<std::chrono::seconds>(now.time_since_epoch());
        auto mills = std::chrono::duration_cast<std::chrono::milliseconds>(now.time_since_epoch());
        auto micros = std::chrono::duration_cast<std::chrono::microseconds>(now.time_since_epoch());
        auto nanos = std::chrono::duration_cast<std::chrono::nanoseconds>(now.time_since_epoch());
        ss << "_" << (mills.count() - seconds.count() * 1000)
           << std::setfill('0') << std::setw(3) << (micros.count() - mills.count() * 1000)
           << std::setfill('0') << std::setw(3) << (nanos.count() - micros.count() * 1000);
    }
    return ss.str();
}

sql::Connection *conn;

sql::Connection *mysql_get_conn(const std::string &hostname_value = "localhost", const std::string &username_value = "rumination",
                                const std::string &password_value = "Rumination0001!", const std::string &dbname_value = "db",
                                const bool &isoptreconnect_value = true)
{
    try
    {
        sql::Driver *driver = get_driver_instance();
        conn = driver->connect(hostname_value, username_value, password_value);
        conn->setSchema(dbname_value);
        return conn;
    }
    catch (const std::exception &e)
    {
        std::stringstream ss;
        ss << "notify-send  'Connect mysql failed!' '";
        ss << e.what() << "!'";
        system(ss.str().c_str());
    }
    return conn;
}

sql::ResultSet *mysql_select_result(const std::string &select_str)
{
    sql::ResultSet *res;
    try
    {
        conn = mysql_get_conn();
        sql::Statement *stmt = conn->createStatement();
        res = stmt->executeQuery(select_str);
    }
    catch (const std::exception &e)
    {
        std::stringstream ss;
        ss << "notify-send  'get select result failed' '";
        ss << select_str << "!'";
        system(ss.str().c_str());
    }
    return res;
}

bool update_sql_result(const std::string &update_str)
{
    try
    {
        conn = mysql_get_conn();
        sql::Statement *stmt = conn->createStatement();
        return stmt->execute(update_str);
    }
    catch (const std::exception &e)
    {
        std::stringstream ss;
        ss << "notify-send  'update failed' '";
        ss << update_str << "!'";
        system(ss.str().c_str());
        return true;
    }
    return true;
}

void mysql_get_conn_demo()
{

    sql::Connection *conn = mysql_get_conn();
    std::cout << std::boolalpha << "conn->isValid():" << conn->isValid() << std::endl;
}

void mysql_select_demo()
{
    std::string select_str = "select * from t3 limit 10;";
    sql::ResultSet *res = mysql_select_result(select_str);
    sql::ResultSetMetaData *res_metadata = res->getMetaData();

    int rows_count = res->rowsCount();
    int cols_count = res_metadata->getColumnCount();
    std::cout << "Rows count " << rows_count << ",columns count:" << cols_count << std::endl;
    while (res->next())
    {
        for (int j = 1; j < cols_count; j++)
        {
            std::cout << res->getString(j) << "\t";
        }
        std::cout << res->getString(cols_count) << std::endl;
    }
    res->close();
    std::cout << get_time_now() << ",thread id:" << std::this_thread::get_id() << std::endl;
}

void mysql_update_demo()
{
    std::stringstream ss;
    ss << "update t3 set author='"
       << "aaa"
       << "' where id=1;";
    bool is_succeed = update_sql_result(ss.str());
    if (!is_succeed)
    {
        std::cout << ss.str() << " execute successfully!" << std::endl;
    }
    else
    {
        std::cout << ss.str() << " execute failed!" << std::endl;
    }
    std::cout << get_time_now() << ",thread id:" << std::this_thread::get_id();
}

int main(int args, char **argv)
{
    // g++-13 -g -std=c++23 -I. main.cpp -lmysqlcppconn -luuid -pthread -o h1;
    mysql_select_demo();

    if (conn->isValid())
    {
        conn->close();
    }

    std::cout << get_time_now() << ",finished id: " << std::this_thread::get_id() << " of " << __LINE__ << " in " << __FUNCTION__ << std::endl;
}

 

Compile

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

 

Run

./h1;

 

 

标签:std,now,chrono,ss,libmysqlcppconn,mysql,update,time,include
From: https://www.cnblogs.com/Fred1987/p/17895040.html

相关文章

  • mysql存json数据时的查询办法
    很多时候mysql的一列当中存的是json格式的数据,这时候如果要查询某个key对应的值的时候要如何查询呢,这里记录一种查询方法:json列的值:{“InventoryMainTypeCode”:1,“InventoryMainTypeName”:“GOOD”}现在要查询InventoryMainTypeCode为xxx或者InventoryMainTypeName为xxx的数......
  • 报错:Client does not support authentication protocol requested by server; consider
    IDEA启动项目登录时显示用户或密码错误或者连接mysql数据库时报错原因:mysql8之前的版本中加密规则是mysql_native_password,而在mysql8之后,加密规则是caching_sha2_password,所以可以需要改变mysql的加密规则打开cmd窗口,登录mysql;mysql-uroot-h127.0.0.1-P3306-p......
  • MySQL中的日期函数
    1.查看日期/时间1.1查看当前的日期/时间(1)NOW():返回当前的日期时间;(2)CURDATE():返回当前的日期;(3)CURTIME():返回当前的时间;SELECTNOW(),CURDATE(),CURTIME();NOW()/CURDATE()/CURTIME()1.2提取指定的日期/时间成分(1)YEAR():提取年份;(2)MONTH():提取月份;(3)DAY():提取天(号/日);(4......
  • liunx二进制包安装5.6MySQL数据库
    官网下载对应的二进制版本安装包https://downloads.mysql.com/archives/community/#解压二进制压缩包[root@localhost~]#wgethttps://cdn.mysql.com/archives/mysql-5.6/mysql-5.6.20-linux-glibc2.5-x86_64.tar.gz[root@localhost~]#tarxfmysql-5.5.32-linux2.......
  • Confluence7.4.6突然爆事务隔离级别问题-解决方案-MySQL session isolation level 'RE
    MySQLsessionisolationlevel'REPEATABLE-READ'isnolongersupported.Sessionisolationlevelmustbe'READ-COMMITTED'.Seehttp://confluence.atlassian.com/x/GAtmDg  成功解决方案:查看http://confluence.atlassian.com/x/GAtmDgFORMYSQL8.X......
  • C# mysql where in 查询时参数化的问题
    大家都知道写代码查询sql的时候是需要对传入的变量参数化的,否则就会有sql注入的风险具体的原因是拼接传入的字符串会被当做sql语句进行解析,如果在传入的参数上做点手脚,就会导致sql的执行超出预期,具有很大的安全隐患,比如当登陆时传入的sql语句是selectcount(*)fromtablewher......
  • MySQL中的date_trunc()函数可以根据不同的时间单位对日期/时间进行截断或截取,返回截断
    转自:https://xkzzz.com/post/235698.htmlMySQL中的date_trunc()函数可以根据不同的时间单位对日期/时间进行截断或截取,返回截断后的日期/时间值。SELECTDATE_TRUNC('day','2019-06-0808:30:45');--截断到天,返回2019-06-0800:00:00SELECTDATE_TRUNC('hour','2019-06-0......
  • sqlalchemy 实现 mysql INSERT INTO...ON DUPLICATE KEY UPDATE语法
    1.前言myql的INSERTINTO...ONDUPLICATEKEYUPDATE语句,简单点来说,就是如果记录不存在,则插入,如果记录存在,则更新。那怎么判断记录存在否?——主键、唯一键。那不是可以使用replace语句吗?——原理上可以,但是sqlalchemyorm中的的实现,是使用merge语法,这个语法有一个限制,就是判......
  • 【题解】AtCoder abc322_f Random Update Query
    传送门:https://atcoder.jp/contests/abc332/tasks/abc332_f容易发现,对于一个位置$i$,$A_i$的最终值是由对$i$的最后一次赋值操作决定的;因此,将所有操作按时间顺序倒过来考虑,则由第$j$次操作决定$A_i$最终值的概率为"在第$(j+1)$~$m$次操作中没有修改过$i$的概率"与"第......
  • IntelliJ IDEA无公网远程连接本地Mysql(提高开发效率!!!)
    IDEA作为Java开发最主力的工具,在开发过程中需要经常用到数据库,如mysql数据库,但是在IDEA中只能连接本地数据库,有时候需要访问其他地方如家里或者公司的数据库,将无法访问,内网的局限性导致我们只能在同一网络访问,无法跨网络访问,所以,本例将介绍如何在异地也可以实现远程连接......