c++ 实现mysql 封装
时间: 2023-05-24 18:06:23 浏览: 190
MySQL封装是将MySQL数据库库函数封装在一个或多个类中,使得它们更容易被使用,同时提供更高层次的抽象和安全性。以下是一个简单的MySQL封装的示例:
#include <mysql/mysql.h>
#include <string>
// 定义一个封装MySQL的类
class MySqlWrapper {
public:
MySqlWrapper(const std::string& host, const std::string& user, const std::string& passwd, const std::string& db, int port = 3306)
: host_(host), user_(user), passwd_(passwd), db_(db), port_(port), conn_(nullptr) {
}
~MySqlWrapper() {
if (conn_) {
mysql_close(conn_);
}
}
bool Connect() {
// 初始化MySQL
if (mysql_library_init(0, nullptr, nullptr) != 0) {
return false;
}
// 创建连接
conn_ = mysql_init(nullptr);
if (conn_ == nullptr) {
return false;
}
// 设置连接选项
mysql_options(conn_, MYSQL_OPT_CONNECT_TIMEOUT, &connect_timeout_);
mysql_options(conn_, MYSQL_OPT_READ_TIMEOUT, &read_timeout_);
mysql_options(conn_, MYSQL_OPT_WRITE_TIMEOUT, &write_timeout_);
// 连接MySQL服务器
if (!mysql_real_connect(conn_, host_.c_str(), user_.c_str(), passwd_.c_str(), db_.c_str(), port_, nullptr, 0)) {
mysql_close(conn_);
conn_ = nullptr;
return false;
}
return true;
}
bool ExecQuery(const std::string& sql) {
if (conn_ == nullptr) {
return false;
}
// 执行SQL语句
if (mysql_query(conn_, sql.c_str()) != 0) {
return false;
}
// 获取结果集
MYSQL_RES* res = mysql_store_result(conn_);
if (res == nullptr) {
return false;
}
// 处理结果集
MYSQL_ROW row;
while ((row = mysql_fetch_row(res)) != nullptr) {
// 处理每一行数据
}
// 释放结果集
mysql_free_result(res);
return true;
}
private:
std::string host_;
std::string user_;
std::string passwd_;
std::string db_;
int port_;
int connect_timeout_ = 5;
int read_timeout_ = 5;
int write_timeout_ = 5;
MYSQL* conn_;
};
// 使用示例
int main() {
MySqlWrapper mysql("localhost", "root", "password", "test");
if (!mysql.Connect()) {
return 1;
}
if (!mysql.ExecQuery("SELECT * FROM mytable")) {
return 2;
}
// 其他操作
return 0;
}
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)