封装数据库的两种方式

仅用于日常代码开发记录,不周之处请多多指教

目标:访问Mysql数据库,能对数据库进行增删改查等操作·

前提:能正常访问#include<mysql.h>

方法一:直接调用mysql库中的方法(这种方法不需要Mysql数据库驱动,简单直接,但是如果封装接口时需要再对其使用套一层函数,方便查询语句使用)

  1. MYSQL *STDCALL mysql_init(MYSQL *mysql);
  2. int STDCALL mysql_options(MYSQL *mysql, enum mysql_option option,const void *arg);
  3. MYSQL *STDCALL mysql_real_connect(MYSQL *mysql, const char *host,const char *user, const char *passwd,const char *db, unsigned int port,const char *unix_socket,unsigned long clientflag);
  4. int STDCALL mysql_query(MYSQL *mysql, const char *q);

实现

头文件必须包含#include<mysql.h>

CommonSQL.h文件

#include <iostream>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <mysql.h>
#include <WinSock.h>
#include <QDebug>
#include <QTextCodec>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QWidget>
#include "CommonDefs.h"

using namespace std;

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

	//单例模式-懒汉
	static CCommonSQL* getInstance();

	//初始化函数
	void init();

	//加载ini文件
	bool loadConfigFile();

	//方法一:连接数据库
	bool ConnectToDB();

	//检验用户登录
	int checkUserByLogonInfo(QString strName,QString strPasswd);
private:
	static CCommonSQL* m_pInstance;
	MYSQL* m_pMysql;

	int m_nPort;
	QString m_strIP;
	QString m_strDatabaseName;
};

CommonSQL.cpp文件

#include "CommonSQL.h"

CCommonSQL* CCommonSQL::m_pInstance = nullptr;

CCommonSQL::CCommonSQL() :
	m_sqlDatabases()
{
	init();
}

CCommonSQL::~CCommonSQL()
{
	delete m_pMysql;
}

CCommonSQL* CCommonSQL::getInstance()
{
	if (m_pInstance == nullptr)
	{
		m_pInstance = new CCommonSQL;
		return m_pInstance;
	}
	return m_pInstance;
}

void CCommonSQL::init()
{
	loadConfigFile();
    
	m_pMysql = new MYSQL;
 	mysql_init(m_pMysql);
 	mysql_options(m_pMysql, MYSQL_SET_CHARSET_NAME, "gbk");
}

bool CCommonSQL::loadConfigFile()
{
	QString strFile("config.ini");
	QFileInfo fileInfo(strFile);
	if (!fileInfo.isFile()) return false;

	QSettings* settings = new QSettings(strFile, QSettings::IniFormat);
	settings->beginGroup("MySQL");
	m_strIP = settings->value("ipAddress").toString();
	m_nPort = settings->value("port").toInt();
	m_strDatabaseName = settings->value("databaseName").toString();
	settings->endGroup();
	return true;
}

bool CCommonSQL::ConnectToDB()
{
 	std::string strIP = m_strIP.toLocal8Bit().data();
						                    //主机    用户名  密码     数据库名	端口
	if (!mysql_real_connect(m_pMysql, strIP.c_str(), "root", "root", m_strDatabaseName.toLatin1(), m_nPort, NULL, 0)) {
		qDebug() << u8"数据库连接失败" << mysql_error(m_pMysql);	
		return false;
	}
 	return true;
} 

int CCommonSQL::checkUserByLogonInfo(QString strName, QString strPasswd)
{

    if (!ConnectToDB()) {
        return SQL_CONNECT_FAILED;
    }
    // 这块实现就是调用QSqlQuery query,实现即可
    bool ret = mysql_query(m_pMysql, "SELECT name FROM user;");

    qDebug() << "ret: "<< ret;
    return SQL_SUCCESS;
}

方法二:需要使用到Mysql数据库的驱动(我本人更偏向于这种,使用方便,灵活)

连接数据库时程序上出现一下提示,

导入驱动请查看该博主的博客:【QT连接Mysql时报错:QSqlDatabase: QMYSQL driver not loaded。解决方案(亲测成功)】_ss_0507的博客-CSDN博客

CommonSQL.h

#pragma once

#include <iostream>
#include <QFile>
#include <QFileInfo>
#include <QSettings>
#include <mysql.h>
#include <WinSock.h>
#include <QDebug>
#include <QTextCodec>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QWidget>
#include "CommonDefs.h"

using namespace std;

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

	//单例模式-懒汉
	static CCommonSQL* getInstance();

	//初始化函数
	void init();

	//加载ini文件
	bool loadConfigFile();

	// 配置数据库初始化连接信息
	void configMysqlInfo();

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

	//断开与数据库的连接
	bool destoryConFromDB();

	//检验用户登录
	int checkUserByLogonInfo(QString strName,QString strPasswd);

	//修改密码
	int modifyUserPasswdByInfo(QString strName, QString strOldPasswd, QString strNewPasswd);

private:
	static CCommonSQL* m_pInstance;
	QSqlDatabase m_sqlDatabases;

	int m_nPort;
	QString m_strIP;
	QString m_strDatabaseName;
};

 CommonSQL.cpp

#include "CommonSQL.h"

CCommonSQL* CCommonSQL::m_pInstance = nullptr;

CCommonSQL::CCommonSQL() :
{
	init();
}

CCommonSQL::~CCommonSQL()
{
	destoryConFromDB();
}

CCommonSQL* CCommonSQL::getInstance()
{
	if (m_pInstance == nullptr)
	{
		m_pInstance = new CCommonSQL;
		return m_pInstance;
	}
	return m_pInstance;
}

void CCommonSQL::init()
{
	loadConfigFile();
	configMysqlInfo();
}

bool CCommonSQL::loadConfigFile()
{
	QString strFile("config.ini");
	QFileInfo fileInfo(strFile);
	if (!fileInfo.isFile()) return false;

	QSettings* settings = new QSettings(strFile, QSettings::IniFormat);
	settings->beginGroup("MySQL");
	m_strIP = settings->value("ipAddress").toString();
	m_nPort = settings->value("port").toInt();
	m_strDatabaseName = settings->value("databaseName").toString();
	settings->endGroup();
	return true;
}

void CCommonSQL::configMysqlInfo()
{
	m_sqlDatabases = QSqlDatabase::addDatabase("QMYSQL");
	m_sqlDatabases.setHostName(m_strIP);
	m_sqlDatabases.setDatabaseName(m_strDatabaseName);
	m_sqlDatabases.setUserName("root");
	m_sqlDatabases.setPassword("root");
}

bool CCommonSQL::ConnectToDatabases()
{
	if (!m_sqlDatabases.open())
	{
		qDebug() << m_sqlDatabases.lastError();
		return false;
	}
	return true;
}

bool CCommonSQL::destoryConFromDB()
{
	m_sqlDatabases.close();
	m_sqlDatabases.removeDatabase("mysql_sxw.db");
	return true;
}

int CCommonSQL::checkUserByLogonInfo(QString strName, QString strPasswd)
{
	try
	{
		if (!ConnectToDatabases())
		{
			return SQL_CONNECT_FAILED;
		}
		QSqlQuery sqlQuery;
		sqlQuery.prepare("SELECT name FROM user WHERE name = :name;");
		sqlQuery.bindValue(":name",strName);
		
		bool ret = sqlQuery.exec();
		if (ret)
		{
			while (sqlQuery.next())
			{
				QString tempName = sqlQuery.value(0).toString();
				if (strName == tempName)
				{
					qDebug() << "tempName : " << tempName;
					QSqlQuery query;
					query.prepare("SELECT passwd FROM user WHERE passwd = :passwd;");
					query.bindValue(":passwd", strPasswd);

					bool res = query.exec();
					if (res)
					{
						while (query.next())
						{
							QString tempPasswd = query.value(0).toString();
							if (tempPasswd == strPasswd)
							{
								qDebug() << "tempPasswd : " << tempPasswd;
								return SQL_SUCCESS;
							}
						}
						return SQL_PASSWD_FAILED;
					}
					else {
						qDebug() << "RES : " << res;
					}
				}
			}
			return SQL_USER_FAILED;
		}
		else
		{
			QString strErrMsg = sqlQuery.lastError().driverText();
			qDebug() << strErrMsg;
			return SQL_QUERY_FAILED;
		}
	}
	catch (...)
	{
		return SQL_CATCH_FAILED;
	}
}

int CCommonSQL::modifyUserPasswdByInfo(QString strName, QString strOldPasswd, QString strNewPasswd)
{
	try
	{
		if (!ConnectToDatabases())
		{
			return SQL_CONNECT_FAILED;
		}
		QSqlQuery sqlQuery;
		sqlQuery.prepare("SELECT name FROM user WHERE name = :name;");
		sqlQuery.bindValue(":name", strName);

		bool ret = sqlQuery.exec();
		if (ret)
		{
			while (sqlQuery.next())
			{
				QString tempName = sqlQuery.value(0).toString();
				if (strName == tempName)
				{
					qDebug() << "tempName : " << tempName;
					QSqlQuery query;
					query.prepare("SELECT passwd FROM user WHERE passwd = :passwd;");
					query.bindValue(":passwd", strOldPasswd);

					bool res = query.exec();
					if (res)
					{
						while (query.next())
						{
							QString tempPasswd = query.value(0).toString();
							if (tempPasswd == strOldPasswd)
							{
								qDebug() << "tempPasswd : " << tempPasswd;
								QSqlQuery query_mod;
								query_mod.prepare("update user set passwd = :strNewPasswd where name = :name;");
								query_mod.bindValue(":strNewPasswd", strNewPasswd);
								query_mod.bindValue(":name", strName);

								if (query_mod.exec())
								{
									return SQL_MODIFY_PASSWD_SUCCESS;
								}
								return SQL_QUERY_FAILED;
							}
						}
						return SQL_MODIFY_PASSWD_FAILED;
					}
					else {
						return SQL_QUERY_FAILED;
					}
				}
			}
			return SQL_USER_FAILED;
		}
		else
		{
			QString strErrMsg = sqlQuery.lastError().driverText();
			qDebug() << strErrMsg;
			return SQL_QUERY_FAILED;
		}
	}
	catch (...)
	{
		return SQL_CATCH_FAILED;
	}
}

config.ini文件

[MySQL]
ipAddress=127.0.0.1
port=3306
databaseName=mysql_sxw

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

枫尘少主

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值