原先那个模板不好用,我来更新一下。

新增了 mysql_error,不然报错怎么死的都不知道。。。


文章目录


db.h

#ifndef DB_H_
#define DB_H_

#include<string>
#include<mysql/mysql.h>
#include<muduo/base/Logging.h>
#include<iostream>

using namespace std;

// 数据库配置信息
static string server = "127.0.0.1";
static string user = "root";
static string password = "123456";
static string dbname = "my12306";

// 数据库操作类
class MySQL {

public:
// 初始化数据库连接
MySQL();

// 释放数据库连接资源
~MySQL();

// 连接数据库
bool connect();

// 更新操作
bool update(string sql);

// 查询操作
MYSQL_RES* query(string sql);

//获取连接
MYSQL* getconnection();

private:
MYSQL *_conn;
};

#endif

db.cpp

#include "db.h"

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");
}
else{
cout<<mysql_error(_conn)<<endl;
}
return p;
}

// 更新操作
bool MySQL::update(string sql)
{
if (mysql_query(_conn, sql.c_str()))
{
LOG_INFO << __FILE__ << ":" << __LINE__ << ":" << sql << "更新失败!";
cout<<mysql_error(_conn)<<endl;
return false;
}

return true;
}

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

return mysql_use_result(_conn);
}

MYSQL* MySQL::getconnection(){
return _conn;
}