C++项目 | 集群聊天服务器 | MYSQL数据库代码封装
本篇博客介绍如何把MYSQL相关代码整合到项目中来
数据层和业务层也要解耦合,就像网络层和业务层一样
业务层不要出现任何的mysql的增删改查
要在业务层和数据层中间加入一层中间层,完成对sql语句的封装
对于业务层要看到的直接操作对象,而不是sql语句
数据层封装了数据库所有的操作
1.检查有没有相应动态库
1
| sudo find /usr -name "libmysqlclient*"
|

没有的话说明只是装了mysql server,没装开发包,执行这个命令安装即可
1
| sudo apt-get install libmysqlclient-dev
|
2.MYSQL相关代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #ifndef DB_H #define BD_H
#include<mysql/mysql.h> #include<string>
using namespace std;
class MySQL { public: MySQL(); ~MySQL(); bool connect(); bool update(string sql); MYSQL_RES *query(string sql);
private: MYSQL *_conn; };
#endif
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| #include "db.h" #include<muduo/base/Logging.h>
static string server = "127.0.0.1"; static string user = "root"; static string password = "123456"; static string dbname = "chat";
MySQL::MySQL() { _conn = mysql_init(nullptr); }
MySQL::~MySQL() { if (_conn != nullptr) mysql_close(_conn); }
bool MySQL::connect() { MYSQL *p = mysql_real_connect(_conn, server.c_str(), user.c_str(), password.c_str(), dbname.c_str(), 3306, nullptr, 0); if (p != nullptr) { mysql_query(_conn, "set names gbk"); } return p; }
bool MySQL::update(string sql) { if (mysql_query(_conn, sql.c_str())) { LOG_INFO << __FILE__ << ":" << __LINE__ << ":" << sql << "更新失败!"; return false; } return true; }
MYSQL_RES *MySQL::query(string sql) { if (mysql_query(_conn, sql.c_str())) { LOG_INFO << __FILE__ << ":" << __LINE__ << ":" << sql << "查询失败!"; return nullptr; } return mysql_use_result(_conn); }
|
3.CMake修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| //顶级CMake
cmake_minimum_required(VERSION 3.0)
project(chat)
set(CMAKE_CXX_FLAGS ${CMAKE_CXX_FLAGS} -g)
set(EXECUTABLE_OUTPUT_PATH ${PROJECT_SOURCE_DIR}/bin)
include_directories(${PROJECT_SOURCE_DIR}/include) include_directories(${PROJECT_SOURCE_DIR}/include/server) include_directories(${PROJECT_SOURCE_DIR}/include/server/db) include_directories(${PROJECT_SOURCE_DIR}/include/client) include_directories(${PROJECT_SOURCE_DIR}/thirdparty)
add_subdirectory(src)
|
将db也加入到了头文件搜索路径
1 2 3 4 5 6 7 8 9 10 11
| //src/server的cmake
aux_source_directory(. SRC_LIST) aux_source_directory(./db DB_LIST)
add_executable(ChatServer ${SRC_LIST} ${DB_LIST})
target_link_libraries(ChatServer muduo_net muduo_base mysqlclient pthread)
|
将mysqlclient也加入了要链接的动态库
4.项目结构图
这是项目目前的目录结构
![image-20250118182054612](https://darling-darling.oss-cn-beijing.aliyuncs.com/image-20250118182054612.png