C++ mysql

1.Install C++ connector

sudo apt install libmysqlcppconn-dev

2.

复制代码
#include <iostream>
#include <cppconn/driver.h> 
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
#include <cppconn/exception.h>

using namespace std;

void mySQL65();

int main(int args, char **argv)
{
    mySQL65();
}

void mySQL65()
{
    try
    {
        sql::Driver *driver;
        sql::Connection *conn;
        sql::Statement *stmt;
        sql::ResultSet *res;

        driver = get_driver_instance();
        conn = driver->connect("tcp://127.0.0.1:3306", "root", "Root0001!");
        conn->setSchema("myDB");

        stmt = conn->createStatement();
        res = stmt->executeQuery("SELECT 'Hello World!' AS _message"); // replace with your statement
        while (res->next())
        {
            cout << "\t... MySQL replies: ";
            /* Access column data by alias or column name */
            cout << res->getString("_message") << endl;
            cout << "\t... MySQL says it again: ";
            /* Access column fata by numeric offset, 1 is the first column */
            cout << res->getString(1) << endl;
        }
        delete res;
        delete stmt;
        delete conn;
    }
    catch (sql::SQLException &e)
    {
        cout << "# ERR: SQLException in " << __FILE__;
        cout << "(" << __FUNCTION__ << ") on line " << __LINE__ << endl;
        cout << "# ERR: " << e.what();
        cout << " (MySQL error code: " << e.getErrorCode();
        cout << ", SQLState: " << e.getSQLState() << " )" << endl;
    }
}
复制代码

 

3.Compile via g++ and inclue mysql connector ,  -I/usr/include/cppconn       -L/usr/lib -lmysqlcppconn

g++ -g -std=c++2a -I. -Wall -I/usr/include/cppconn  *.cpp ./Model/*.cpp -o h1 -luuid -lpthread -L/usr/lib -lmysqlcppconn

4.Run the compiled program

 

posted @   FredGrit  阅读(81)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示