c++使用mysqlclient库开发mysql

使用libmysqlclient库对mysql进行c++开发

安装

bash 复制代码
sudo apt update && sudo apt install libmysqlclient-dev -y

封装客户端

一般都是封装一个客户端类进行开发,如下的mysql.h:

cpp 复制代码
#pragma once
#include <mysql/mysql.h>
#include <string>
#include <iostream>

// 数据库操作类
class MySQL {
public:
    MySQL(); // 初始化数据库连接资源
    ~MySQL(); // 释放数据库连接资源
    bool connect(); // 连接数据库
    bool update(std::string sql); // 更新(insert, delete, update都是这个接口)
    MYSQL_RES *query(std::string sql); // 查询操作
    MYSQL* getConnection();     // 获取连接
private:
    MYSQL *_conn; //一条连接
};

mysql.cpp如下:

cpp 复制代码
#include "mysql.h"

// 数据库配置信息
static std::string server = "127.0.0.1";
static uint16_t port = 3306;
static std::string user = "root";
static std::string password = "123456";
static std::string dbname = "chat";

// 初始化数据库连接资源
MySQL::MySQL() {
    _conn = mysql_init(nullptr);
}

// 释放数据库连接资源
MySQL::~MySQL() {
    if (_conn) {
        mysql_close(_conn);
    }
}

// 连接数据库
bool MySQL::connect() {
    MYSQL *p = mysql_real_connect(_conn, server.c_str(), user.c_str(), password.c_str(), dbname.c_str(), port, nullptr, 0);
    if (p) {
        // C和C++代码默认的编码字符是ASCII,如果不设置,从MySQL上拉下来的中文会乱码
        mysql_query(_conn, "set names gbk");
        std::cout << "connect mysql success!" << std::endl;
    } 
    else {
        std::cout << "connect mysql failed!" << std::endl;
    }
    return p; //空不就是false吗
}

// 更新(insert,delete,update都是这个接口)
bool MySQL::update(std::string sql) {
    if (mysql_query(_conn, sql.c_str())) {
        std::cout << __FILE__ << ":" << __LINE__ << ":" << sql << "更新失败!" << std::endl;
        return false;
    }
    std::cout << __FILE__ << ":" << __LINE__ << ":" << sql << "更新成功!" << std::endl;
    return true;
}

// 查询操作
MYSQL_RES *MySQL::query(std::string sql) {
    if (mysql_query(_conn, sql.c_str())) {
        std::cout << __FILE__ << ":" << __LINE__ << ":" << sql << "查询失败!" << std::endl;
        return nullptr;
    }
    return mysql_use_result(_conn);
}

// 获取连接
MYSQL* MySQL::getConnection() {
    return _conn;
}

使用示例

可参考https://github.com/1412771048/chatserver/tree/main

cpp 复制代码
#include "mysql.h"
#include <iostream>

int main() {
    MySQL mysql;
    if (mysql.connect()) {
        char sql[1024] = {0};
            snprintf(sql, sizeof(sql), "select name from user where name='%s'", name.c_str());
            mysql.query(sql);
    } 
}

编译:

cpp 复制代码
g++ 1.cpp mysql.cpp -lmysqlclient
相关推荐
Victoria.a1 小时前
string类详解
数据结构·c++
转调3 小时前
第九章:内存池的调整与测试
c++·内存池
XY_墨莲伊4 小时前
【算法设计与分析】实验5:贪心算法—装载及背包问题
c语言·数据结构·c++·算法·贪心算法·排序算法
KuaCpp5 小时前
搜索与图论复习2最短路
c++·算法·图论
Lenyiin5 小时前
《 C++ 点滴漫谈: 二十五 》空指针,隐秘而危险的杀手:程序崩溃的真凶就在你眼前!
c++·nullptr·lenyiin·c++关键字
zxb@hny6 小时前
vscode命令面板输入 CMake:build不执行提示输入
c++·ide·vscode
c-c-developer6 小时前
C++ Primer 自定义数据结构
数据结构·c++
不会打代码呜呜呜呜6 小时前
小白零基础--CPP多线程
开发语言·c++·算法
涛ing6 小时前
【5. C++ 变量作用域及其深入探讨】
java·linux·c语言·开发语言·c++·ubuntu·vim
SY师弟7 小时前
蓝桥杯单片机第七届省赛
c语言·c++·单片机·嵌入式硬件·职场和发展·蓝桥杯