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
相关推荐
j_xxx404_5 小时前
Linux:静态链接与动态链接深度解析
linux·运维·服务器·c++·人工智能
bqq198610265 小时前
MySQL 5.7 与 MySQL 8.0 的主要区别
数据库·mysql
c++之路6 小时前
C++23概述
java·c++·c++23
摇滚侠7 小时前
DBeaver 导入数据库 导入 SQL 文件 MySQL 备份恢复
java·数据库·mysql
学涯乐码堂主7 小时前
有趣的“打擂台算法”
c++·算法·青少年编程·gesp
云栖梦泽8 小时前
Linux内核与驱动:14.SPI子系统
linux·运维·服务器·c++
Gary Studio8 小时前
安卓HAL C++基础-智能指针
开发语言·c++
还是阿落呀8 小时前
基本控制结构2
c++
Frank_refuel8 小时前
终端环境下:Ubuntu 22.04.1 安装 MySQL 数据库
数据库·mysql·ubuntu
多思考少编码9 小时前
PAT甲级真题1001 - 1005题详细题解(C++)(个人题解)
c++·python·最短路·pat·算法竞赛