C++聊天集群服务器2

发布时间 2023-11-27 11:26:20作者: 桂洛克船长

​ 总体项目结构如下:

image-20231127111644277

一、数据库的封装

​ db.h如图代码量不多

​ db.cpp:

#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)
    {
        // c和C++代码默认编码字符是ASCII,如果不设置,从mysql拉下来的就是乱码
        mysql_query(_conn, "set names gbk");
        LOG_INFO << "connect mysql success!";
    }
    else
    {
        LOG_INFO << "connect mysql fail!";
    }
    return p;
}
// 更新操作
bool MySQL::update(string sql)
{
    if (mysql_query(_conn, sql.c_str()))
    {
        LOG_INFO << __FILE__ << ":" << __LINE__ << ":"
                 << sql << "MySQL更新失败!";
        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);
}


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

二、用户类的定义

​ user.hpp:

image-20231127111845201

三、User表的操作类

​ 定义与实现:

image-20231127111942418

image-20231127112007002

四、测试注册业务

​ 使用cmake编译完成后,开两个shell一个作为服务器,一个作为客户端测试。测试结果如下:

image-20231127112145817

可以看见数据库连接并更新成功,登录数据库看一下:

image-20231127112252928

​ 可以看见第24条为刚才插入的数据。