mysql api的封装

 


头文件

#pragma once
#include<mysql.h>
#include<iostream>
#include<string>
class MysqlConn
{
public:
	//初始化数据库连接
	MysqlConn();
	//释放数据库连接
	~MysqlConn();
	//连接数据库
	bool connect(std::string user, std::string password, std::string dbName, std::string ip, unsigned short port = 3306);
	//更新数据库insert update delete
	bool update(std::string sql);
	//查询数据库
	bool query(std::string sql);
	//遍历结果集
	bool next();
	//得到结果集中的字段值
	std::string value(int index);
	//事务操作
	bool transaction();
	//提交事务
	bool commit();
	//事务回滚
	bool rollback();
private:
	void freeResult();
	MYSQL* m_conn = nullptr;
	MYSQL_RES* m_result = nullptr;
	MYSQL_ROW m_row = nullptr;
};

cpp文件

#include "MysqlConn.h"

MysqlConn::MysqlConn()
{
	m_conn = mysql_init(nullptr);
	//使用编码
	mysql_set_character_set(m_conn, "utf8");

}

MysqlConn::~MysqlConn()
{
	if (m_conn != nullptr)
	{
		mysql_close(m_conn);
	}
	freeResult();
}
bool MysqlConn::connect(std::string user, std::string password, std::string dbName, std::string ip, unsigned short port = 3306)
{
	MYSQL* ptr= mysql_real_connect(m_conn, ip.c_str(), user.c_str(), password.c_str(), dbName.c_str(), port, nullptr, 0);

	return ptr!=nullptr;

}

bool MysqlConn::update(std::string sql)
{
	if (mysql_query(m_conn, sql.c_str()))
	{
		return false;
	}
	return true;
}

bool MysqlConn::query(std::string sql)
{
	freeResult();
	if (mysql_query(m_conn, sql.c_str()))
	{
		return false;
	}
	m_result=mysql_store_result(m_conn);
	return true;
}

bool MysqlConn::next()
{
	if (m_result != nullptr)
	{
		m_row=mysql_fetch_row(m_result);
	}
	return false;
}

std::string MysqlConn::value(int index)
{
	int columnNum = mysql_num_fields(m_result);
	if (index >= columnNum || index < 0)
	{
		return std::string();
	}
	char* val = m_row[index];
	unsigned long length=mysql_fetch_lengths(m_result)[index];
	return std::string(val,length);
}

bool MysqlConn::transaction()
{

	return mysql_autocommit(m_conn, false);
}

bool MysqlConn::commit()
{
	return mysql_commit(m_conn);
}

bool MysqlConn::rollback()
{
	return mysql_rollback(m_conn);
}

void MysqlConn::freeResult()
{
	if (m_result)
	{
		mysql_free_result(m_result);
		m_result = nullptr;
	}
}

posted @   LiviaYu  阅读(28)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示