聊天服务器(7)数据模块

目录

Mysql数据库代码封装

业务层代码不要直接写数据库,因为业务层和数据层的代码逻辑也想完全区分开。万一不想存储mysql,想存redis的话,就要改动大量业务代码。解耦合就是改起来很方便。

首先需要安装mysql以及libmysqlclient-dev这个开发包

依赖文件加一个

头文件搜索路径加一个

头文件与源文件

cpp 复制代码
#ifndef DB_H
#define DB_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
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++代码默认的编码字符是
        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);
}

添加一条数据,注册业务

相关推荐
恋猫de小郭3 小时前
Android Studio 正式版 10 周年回顾,承载 Androider 的峥嵘十年
android·ide·android studio
m0_465215793 小时前
TCP & UDP Service Model
服务器·网络·tcp/ip
chian-ocean6 小时前
从理论到实践:Linux 进程替换与 exec 系列函数
linux·运维·服务器
aaaweiaaaaaa6 小时前
php的使用及 phpstorm环境部署
android·web安全·网络安全·php·storm
敖行客 Allthinker6 小时前
从 UTC 日期时间字符串获取 Unix 时间戳:C 和 C++ 中的挑战与解决方案
linux·运维·服务器·c++
工程师老罗8 小时前
Android记事本App设计开发项目实战教程2025最新版Android Studio
android
norsd9 小时前
MongoDb user自定义 role 添加 action(collStats, EstimateDocumentCount)
服务器·数据库·mongodb
_Eden_9 小时前
Keepalived高可用集群企业应用实例一
运维·服务器
画船听雨眠aa10 小时前
gitlab云服务器配置
服务器·git·elasticsearch·gitlab
s_little_monster11 小时前
【Linux】从硬件到软件了解进程
linux·运维·服务器·经验分享·笔记·学习·学习方法