C++ MySql驱动

本文详细介绍了MySQL数据库的特点,如开源免费、易用性、高可靠性和性能,以及其在C++中的封装接口,包括MySQL_Driver和MySQL_Connection类,用于连接、执行SQL和处理查询结果。
摘要由CSDN通过智能技术生成

 MySQL数据库的优势包括:

1. 开源免费:MySQL是一款开源的关系型数据库管理系统,可以免费使用和修改。
2. 易用性:MySQL提供了简单直观的命令行界面和图形化界面,使得用户能够轻松地创建、查询和管理数据库。
3. 可靠性:MySQL具有良好的稳定性和可靠性,能够处理大规模数据和高并发访问。
4. 高性能:MySQL采用了多种优化策略和技术,如索引、缓存、分区等,以提供快速的读写操作和响应时间。
5. 扩展性:MySQL支持水平扩展和垂直扩展,可以方便地增加或减少服务器的数量、内存和存储容量,以满足不断增长的需求。
6. 兼容性:MySQL遵循SQL标准,与其他常见的数据库系统兼容,能够无缝迁移和集成现有的数据和应用程序。
7. 安全性:MySQL提供了灵活而强大的安全特性,如用户权限控制、SSL加密通信等,保护敏感数据的安全性。
8. 社区支持:MySQL拥有庞大的开源社区,用户可以通过社区获取帮助、分享经验和参与开发,获得及时的技术支持。

MySQL真可谓是集万千宠爱于一身啊,只可惜对于初学者而言,门槛似乎高了那么一点点,这里我针对MySQL的常用语法汇总写了这样一个库文件(支持跨平台使用),方便大家使用:

接口声明:

/************************************************************************/
/*  MySQL_Driver MySQL_Connection                                       */
/*  利用MySql API接口,将其进行封装,旨在提供一个方便、快捷的访问接口   */
/*  作者:老狼                                                          */
/*  时间:2023/08/26                                                    */
/*  版本:1.0		                                                    */
/************************************************************************/
#ifndef MYSQL_DRIVER_H
#define MYSQL_DRIVER_H

#include <string>
#include <map>
#include <vector>
#include <iostream>
#include "mysql.h"

using namespace std;
typedef std::map<std::string, std::string> FieldsValue;

class MySQL_Driver
{
protected:
	//代表一个到数据库的连接
	MYSQL *mysql;
	//操作的结果集
	MYSQL_RES *dataSet;
	//返回查询得到的结果数
	my_ulonglong num;
	//错误提示信息
	std::string error;
	//查询语句返回一条结果
	FieldsValue record;
	//查询结果集
	std::vector<FieldsValue> records;
	//查询表结构的字段名称
	std::vector<std::string> fields;

public:
	MySQL_Driver(void);
	virtual ~MySQL_Driver(void);
	
	// 连接驱动
	unsigned int connect(std::string host, std::string database, std::string user, std::string password, unsigned int port=3306);
	//执行sql语句
	unsigned int exec(std::string sql);
	//返回查询得到的结果
	std::vector<FieldsValue> fieldValues();
	//返回错误信息
	std::string errorCode();
	//返回查询表结构字段名称
	std::vector<std::string> fieldsName();
	//向数据库中插入一条数据
	unsigned int insert(std::string table, FieldsValue *data);
	//返回最后一个自动增量的值
	unsigned long getlastid();
	//返回一条sql语句影响的行数
	unsigned long numRowsAffected();
	//根据条件修改一条数据
	unsigned int update(std::string table, FieldsValue *data, std::string condition);
	//根据条件删除数据
	unsigned int remove(std::string table, std::string condition);

	//判断数据库是否连接
	bool connected();
	//断开数据库连接
	void disconnected();
};

class MySQL_Connection
{
public:
	MySQL_Connection(MySQL_Driver* pMysqlDriver);
	virtual ~MySQL_Connection(void);
	//执行sql语句
	bool exec(std::string sql);	
	//取字符串值
	bool stringValue(std::string &str, std::string fieldName,int nFieldLen=-1);
	//取整型值
	bool intValue(long &lVal, std::string fieldName);
	//取浮点型值
	bool floatValue(double &lVal, std::string fieldName);
	//返回一条sql语句影响的行数
	long numRowsAffected();
	//记录下移
	bool next();
	//记录上移
	bool previous();
	//记录开头
	bool first();
	//记录结尾
	bool last();
	//是否到记录尾
	bool eof();
	//是否到记录头
	bool bof();

private:
	//当前值在记录集中的问题
	int index;
	//记录集
	std::vector<FieldsValue> records;
	//驱动
	MySQL_Driver	*m_pMysqlDriver;
};

#endif

接口定义:

#include "stdafx.h"
#include "MySQL_Driver.h"
#include <assert.h>

MySQL_Driver::MySQL_Driver(void)
{
	mysql = NULL;
	num = 0;
	error="";
	dataSet = NULL;
}

MySQL_Driver::~MySQL_Driver(void)
{

}

// 设置数据库连接参数
unsigned int MySQL_Driver::connect(std::string host,std::string database, std::string user, std::string password,unsigned int port/*=3306*/)
{
	if (connected())
		return 0;

	MYSQL *con;
	if(mysql == NULL)
	{
		mysql = ::mysql_init(NULL);

		if (mysql == NULL)
		{
			error = "初始化mysql错误";
			return 1;
		}
	}

	my_bool my_true = true;
	mysql_options(mysql, MYSQL_OPT_RECONNECT, &my_true);
	con = ::mysql_real_connect(mysql,host.c_str(),user.c_str(),password.c_str(),NULL,port,NULL,0);
	if(con == NULL)
	{
		error = ::mysql_error(mysql);
		return ::mysql_errno(mysql);
	}

	// mysql_options(mysql, MYSQL_SET_CHARSET_NAME, "gb2312");
	::mysql_set_character_set(mysql,"gb2312");

	unsigned int re;
	re = ::mysql_select_db(mysql,database.c_str());
	if(re != 0)
	{
		error += ::mysql_error(mysql);
	}

	return re;
}

//查询数据库
unsigned int MySQL_Driver::exec(std::string sql)
{
	if(dataSet != NULL )
		mysql_free_result(dataSet);

	unsigned int re;
	if( mysql == NULL) return 1;
	assert(!sql.empty());
	re = ::mysql_query(mysql,sql.c_str());
	if(re == 0)
	{
		dataSet = ::mysql_store_result(mysql);
		num = ::mysql_affected_rows(mysql);
		record.clear();
		records.clear();
		fields.clear();
	}
	else
	{
		re = ::mysql_errno(mysql);
		error = ::mysql_error(mysql);
		std::cout<<error<<std::endl;
	}

	return re;
}

/*获取查询得到的所有结果*/
std::vector<FieldsValue> MySQL_Driver::fieldValues()
{
	MYSQL_ROW row;
	unsigned int i;
	FieldsValue tmp;
	assert(mysql != NULL);
	if(records.size() > 0) return records;
	if(dataSet != NULL)
	{
		fieldsName();
		while(row = mysql_fetch_row(dataSet))
		{
			if(row != NULL)
			{
				for(i=0;i<fields.size();i++)
				{
					if ((char *)row[i] != NULL)
					{
						tmp[fields[i]] = (char *)row[i];
					}
					else
					{
						tmp[fields[i]] = "";
					}
				}

				records.push_back(tmp);
			}
		}
	}

	return records;
}

//返回错误信息
std::string MySQL_Driver::errorCode()
{
	return error;
}

//返回查询后的列值
std::vector<std::string> MySQL_Driver::fieldsName()
{
	/*
	field = mysql_fetch_fields(dataSet);
	然后通过field[i].name访问在此有错误,不知道为什么,可能是mysql的bug
	*/
	MYSQL_FIELD *field;
	assert(mysql != NULL);
	if(fields.size()>0) return fields;
	while(field = mysql_fetch_field(dataSet))
	{
		fields.push_back(field->name);
	}

	return fields;
}

//向数据库中插入一条数据
unsigned int MySQL_Driver::insert(std::string table, FieldsValue *data)
{
	FieldsValue::const_iterator iter;
	std::string sql;
	int flag=0;
	assert(mysql != NULL);
	assert(!table.empty());
	assert(data != NULL);
	for(iter = data->begin();iter!= data->end();iter++)
	{
		if(flag == 0)
		{
			sql = "insert into ";
			sql += table;
			sql += " set ";
			sql += iter->first;
			sql += "='";
			sql += iter->second;
			sql += "'";
			flag++;
		}
		else
		{
			sql += ",";
			sql += iter->first;
			sql += "='";
			sql += iter->second;
			sql += "'";
		}
	}

	return exec(sql);
}

//返回最后一个自动增量的值
unsigned long MySQL_Driver::getlastid()
{
	return (unsigned long)::mysql_insert_id(mysql);
}

//返回一条sql语句影响的行数
unsigned long MySQL_Driver::numRowsAffected()
{
	return (unsigned long)num;
}

//根据条件修改一条数据
unsigned int MySQL_Driver::update(std::string table, FieldsValue *data, std::string condition)
{
	FieldsValue::const_iterator iter;
	std::string sql;
	int flag=0;
	assert(mysql != NULL);
	assert(!table.empty());
	assert(data != NULL);
	for(iter = data->begin();iter!= data->end();iter++)
	{
		if(flag == 0)
		{
			sql  = "update ";
			sql += table;
			sql += " set ";
			sql += iter->first;
			sql += "='";
			sql += iter->second;
			sql += "'";
			flag++;
		}
		else
		{
			sql += ",";
			sql += iter->first;
			sql += "='";
			sql += iter->second;
			sql += "'";
		}
	}

	if(!condition.empty())
	{
		sql += " where ";
		sql += condition;
	}

	return exec(sql);
}

//根据条件删除数据
unsigned int MySQL_Driver::remove(std::string table, std::string condition)
{
	std::string sql;
	assert(mysql != NULL);
	assert(!table.empty());
	sql = "delete from ";
	sql += table;
	if(!condition.empty())
	{
		sql += " where ";
		sql += condition;
	}

	return exec(sql);
}

bool MySQL_Driver::connected()
{
	if (mysql == NULL || mysql->host==NULL)
		return false;

	static int lastcontime = 0;
	if ((GetTickCount()-lastcontime) > 60000)
	{
		if (mysql_ping(mysql)==0)
		{
			lastcontime = GetTickCount();
			return true;
		}
		else
			return false;
	}
	else
	{
		return true;
	}
}

void MySQL_Driver::disconnected()
{
	if(dataSet != NULL)
		::mysql_free_result(dataSet);
	fields.clear();
	error = "";
	record.clear();
	records.clear();
	::mysql_close(mysql);
	mysql = NULL;
}

//

MySQL_Connection::MySQL_Connection(MySQL_Driver* pMysqlDriver)
{
	m_pMysqlDriver = pMysqlDriver;
}


MySQL_Connection::~MySQL_Connection(void)
{
}

bool MySQL_Connection::exec(std::string sql)
{
	if (m_pMysqlDriver != NULL)
	{	
		if (m_pMysqlDriver->exec(sql)==0)
		{
			records = m_pMysqlDriver->fieldValues();
			index = 0;
			if (records.size() > 0)
				return true;
			else
				return false;
		}
		else
			return false;
	}

	return false;
}

bool MySQL_Connection::stringValue(std::string &str, std::string fieldName,int nFieldLen/*=-1*/)
{
	str = records[index][fieldName];
	return true;
}

bool MySQL_Connection::intValue(long &lVal, std::string fieldName)
{
	const char* pszVal = records[index][fieldName].c_str();
	lVal = atoi(pszVal);
	return true;
}

bool MySQL_Connection::floatValue(double &lVal, std::string fieldName)
{
	const char* pszVal = records[index][fieldName].c_str();
	lVal = atof(pszVal);
	return true;
}

long MySQL_Connection::numRowsAffected()
{
	if (m_pMysqlDriver != NULL)
	{
		return m_pMysqlDriver->numRowsAffected();
	}

	return 0;
}

bool MySQL_Connection::next()
{
	if (m_pMysqlDriver == NULL) return false;

	if (++index >= (int)m_pMysqlDriver->numRowsAffected()) return false;
	
	return true;
}

bool MySQL_Connection::previous()
{
	if (m_pMysqlDriver == NULL) return false;

	if (--index < 0) return false;

	return true;
}

bool MySQL_Connection::first()
{
	if (m_pMysqlDriver == NULL) return false;
	index= 0;
	if (index >= (int)m_pMysqlDriver->numRowsAffected()) return false;

	return true;
}

bool MySQL_Connection::last()
{
	if (m_pMysqlDriver == NULL) return false;
	index= m_pMysqlDriver->numRowsAffected() - 1;
	if (index >= (int)m_pMysqlDriver->numRowsAffected()) return false;
	if (index < 0) return false;

	return true;
}

bool MySQL_Connection::eof()
{
	if (m_pMysqlDriver == NULL) return false;
	if (index == m_pMysqlDriver->numRowsAffected()) return true;
	return false;
}

bool MySQL_Connection::bof()
{
	if (m_pMysqlDriver == NULL) return false;
	if (index == 0 && m_pMysqlDriver->numRowsAffected()>0) return true;
	return false;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值