跳至主要內容

数据库编程部分的实现

张威大约 2 分钟mysqlmysql连接池

数据库编程部分的实现

在VS上使用MySQL的头文件和库文件的配置

  1. 右键项目 - C/C++ - 常规 - 附加包含目录,填写mysql.h头文件的路径

  2. 右键项目 - 链接器 - 常规 - 附加库目录,填写libmysql.lib的路径

  3. 右键项目 - 链接器 - 输入 - 附加依赖项,填写libmysql.lib库的名字

  4. 把libmysql.dll动态链接库(Linux下后缀名是.so库)放在工程目录下

代码

//public.h
/*
 * 这是一个公共的头文件
*/
#ifndef _PUBLIC_H
#define _PUBLIC_H

//日志
#define LOG(str) \
    cout << __FILE__ << ":" << __LINE__ << " " <<   \
    __TIMESTAMP__ << ":" << str << endl;


#endif //_PUBLIC_H

下面是对MySQL操作的封装

//connection.h
/*
 * 实现MySQL数据库的操作
*/

#ifndef _CONNECTION_H
#define _CONNECTION_H
#include <string>
#include <mysql/mysql.h>

using std::string;

class Connection {
public:
    Connection();
    ~Connection();

    //数据库的连接操作
    bool connection(string ip, unsigned short port, string user, string passward, string dbname);
    
    //更新操作 insert delete update
    bool update(string sql);

    //查询操作select
    MYSQL_RES* query(string sql);
private:
    MYSQL* _conn;    //表示和MySQL的一条连接
};

#endif  // _CONNECTION_H
//connection.cc
#include <iostream>
#include "connection.h"
#include "public.h"

using std::cout;
using std::endl;

Connection::Connection() {
    //初始化
    _conn = mysql_init(nullptr);
}

//释放资源
Connection::~Connection() {
    if(_conn != nullptr) {
        mysql_close(_conn);
    }
}

bool Connection::connection(string ip, unsigned short port, 
string user, string passward, string dbname) {
    //建立连接
    MYSQL* p = mysql_real_connect(_conn, ip.c_str(), user.c_str(),
     passward.c_str(),dbname.c_str(), port, nullptr, 0);
     return p != nullptr;
}

bool Connection::update(string sql) {
    //更新操作 insert delete update
    if(mysql_query(_conn, sql.c_str())) {
        LOG("更新失败:" +  sql);
        return false;
    }
    return true;
}

MYSQL_RES* Connection::query(string sql) {
    if(mysql_query(_conn, sql.c_str())) {
        LOG("查询失败" + sql);
    }
    return mysql_use_result(_conn);
}
//main.cc
#include <iostream>
#include "connection.h"
#include "public.h"

using std::cout;
using std::endl;

int main() {
    Connection conn;
    char sql[1024] = {0};
    sprintf(sql, "insert into user(name, age, sex) values('%s', %d, '%s')",
     "guan yu", 33, "male");

    bool ret = conn.connection("127.0.0.1", 3306, "root", "147258", "school");
    if(!ret) {
        LOG("连接失败");
    }
    conn.update(sql);
}
$g++ connection.cc main.cc -o main -I /usr/include/ -lmysqlclient