linux下使用ConnectorC/C++连接Mysql

1. 下载安装了 MySQL Connector/C++

sudo apt update
sudo apt install libmysqlcppconn-dev

查看下载安装的位置命令:

dpkg -L libmysqlcppconn-dev	//验证安装位置
dpkg -L libmysqlcppconn-dev | grep '\.so$'//查询库的位置
dpkg -L libmysqlcppconn-dev | grep '\.h$'//查询头文件的位置
  1. 编写C++连接mysql的代码:使用的是默认的3306端口,数据库密码是000522,必须要有一个test数据库;
#include <mysql_driver.h>
#include <mysql_connection.h>
#include <cppconn/statement.h>
#include <cppconn/resultset.h>
#include <cppconn/exception.h>
#include <iostream>

using namespace std;
using namespace sql::mysql;

int main() {
    try {
        // 获取 MySQL 驱动程序实例
        MySQL_Driver *driver = sql::mysql::get_mysql_driver_instance();

        // 创建连接对象
        std::unique_ptr<sql::Connection> con(driver->connect("tcp://127.0.0.1:3306", "root", "000522"));

        // 使用指定的数据库
        con->setSchema("test");

        // 执行查询
        std::unique_ptr<sql::Statement> stmt(con->createStatement());
        std::unique_ptr<sql::ResultSet> res(stmt->executeQuery("SELECT 'Hello World!' AS message"));

        // 处理查询结果
        while (res->next()) {
            cout << "MySQL replies: " << res->getString("message") << endl;
        }
    } catch (sql::SQLException &e) {
        cerr << "SQLException: " << e.what() << endl;
        return 1;
    }

    return 0;
}

3.编译运行

g++ mysql_example.cpp -o mysql_example -lmysqlcppconn
./mysql_example


4、成功输出:

MySQL replies: Hello World!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值