Qt 封装Sqlite类,及问题出现QSqlDatabase: QSQLITE driver not loaded 解决

使用qt 自带的QSql 模块连接Sqlite类,封装简易版本,还可以继续完善。
头文件 :

#pragma once

///
//  DataBase.h
//  description:Sqlite
//  Created on:      12-08-2020 21:12:15
//  Original author: karlchan
///

#include 
#include 
#include "projectdatautils_global.h"

#define  OUT   
const QString POSTGRESQL_DRIVE = "QPSQL";
const QString SQLITE_DRIVE = "QSQLITE";
const QString MYSQL_DRIVE = "QMYSQL";
const QString ODBC_DRIVE = "QODBC";
const QString DB2_DRIVE = "QDB2";

typedef struct PROJECTDATAUTILS_EXPORT tagSqlConnInfo// 存储SQL连接信息
{
	QSqlDatabase db;
	QString hostName;//
	QString user;
	QString passwd;
	QString dbName;
	QString connName;
	QString connType;
	int port;
	tagSqlConnInfo() {
		hostName = "";
		user = "";
		passwd = "";
		dbName = "";
		connName = QSqlDatabase::defaultConnection;
		connType = SQLITE_DRIVE;
		port = 0;
	}

}SqlConnInfo;

class PROJECTDATAUTILS_EXPORT DataBase : public QObject
{
	Q_OBJECT

public:
	DataBase(QObject *parent);
	virtual ~DataBase();
	
	bool initDb(SqlConnInfo& info);
	bool deinitDb();
	bool openDb();
	bool closeDb();

public:

	bool createTable(QString tbName,QString columns);
	bool deleteTable(QString tbName);
	
	QSqlQuery queryRecord(QString tbName, QString attribute);//查询关键字 
	bool insertRecord(QString tbName, QString columnsValue);//插入数据 不指定列,按所创建的一一对应值 "ddd,abc" 
	bool insertRecord(QString tbName, QString columns, QString columnsValue);//插入数据  "column1,column2" "ddd,abc"

	bool beginTransaction();
	bool rollbackTransaction();
	bool commitTransaction();
	bool isExistTable(const QString &tbName);

	bool execSQL(const QString &sql, OUT QList<QStringList> &result);
	bool execSQL(const QString &sql);

public:
	QSqlDatabase getSqlDbObject() const ;
protected:
	SqlConnInfo m_connInfo;

};

cpp文件:

#include "DataBase.h"
#include 
#include 
#include 
#include 
#include 
#include 
#include 
DataBase::DataBase(QObject *parent)

{

}

DataBase::~DataBase()
{

}


bool DataBase::initDb(SqlConnInfo& info)
{
	try {

		m_connInfo = info;
		if (QSqlDatabase::contains(m_connInfo.connName)) {
			m_connInfo.db = QSqlDatabase::database(m_connInfo.connName);
		}
		else {
			m_connInfo.db = QSqlDatabase::addDatabase(m_connInfo.connType, m_connInfo.connName);
		}

		m_connInfo.db.setDatabaseName(m_connInfo.dbName);
		//m_connInfo.db.setHostName();...

	}
	catch (...) {
		//LogError(QString("Add Database Failed Exception!"));
		qDebug() << ("initDb  Failed Exception!");
		return false;
	}
	return true;
}

bool DataBase::deinitDb()
{
	return closeDb();
}



bool DataBase::openDb()
{
	try {
		if (!m_connInfo.db.open()) {
			//	LogError(QString("Open Database Failed!"));
			qDebug() << "Open Database Failed!";
			return false;
		}
	}
	catch (...) {
		//	LogError(QString("Open Database Failed!"));
		qDebug() << "Open Database Exception!";
		return false;
	}
	return true;
}

bool DataBase::closeDb()
{
	if (m_connInfo.db.isOpen()) {
		m_connInfo.db.close();
	}
	return true;
}

/*
* createTable,创建表
*  tbName,数据表名
* @param columns,表结构,格式(字段 类型,字段 类型),注意日期自动生成无需包含,例:"attribute varchar,type varchar"
* @return true/false
*/

bool DataBase::createTable(QString tbName, QString columns)
{
	//1.validata
	assert(!tbName.isEmpty() && !columns.isEmpty());

	//2.Create Table
	try {
		QSqlQuery query(m_connInfo.db);
		bool success = query.exec(QString("CREATE TABLE IF NOT EXISTS %1 (%2, last_time DATETIME)").arg(tbName).arg(columns));
		if (success) {
			qDebug() << QStringLiteral("数据库表创建成功!\n") + tbName;
			return true;
		}
		else {
			qDebug() << QStringLiteral("数据库表创建失败!\n") + tbName;
			return false;
		}
	}
	catch (...)
	{
		qDebug() << ("createTable  Failed Exception!");
		return false;
	}
}

bool DataBase::deleteTable(QString tbName)
{
	//1.validata
	assert(!tbName.isEmpty());

	//2.Drop
	try
	{
		QSqlQuery query(m_connInfo.db);
		bool success = query.exec("DROP TABLE IF EXISTS " + tbName + " ;");
		if (success) {
			qDebug() << QObject::tr("数据库表删除成功!\n");
			return true;
		}
		else {
			qDebug() << QObject::tr("数据库表删除失败!\n");
			return false;
		}
	}
	catch (...) {
		qDebug() << ("deleteTable  Failed Exception!");
		return false;
	}
}


/**
* @brief readDB,关键字查询
* @param tb_name,数据表名
* @param attribute,查询关键字,格式(字段名:字段值,例:"id:001"
* @return query,查询结果集
*/
QSqlQuery DataBase::queryRecord(QString tbName, QString attribute)
{
	//1.validata
	assert(!tbName.isEmpty() && !attribute.isEmpty());

	//2.read 
	try
	{
		QSqlQuery query(m_connInfo.db);
		QStringList parts = attribute.split(":");
		query.prepare(QString("SELECT * FROM %1 WHERE %2=%3 ORDER by last_time DESC").arg(tbName).arg(parts[0]).arg(parts[1]));//ORDER by TIME DESC
		bool success = query.exec();
		if (!success)
		{
			QSqlError lastError = query.lastError();
			qDebug() << lastError.driverText() << QStringLiteral("查询失败");
		}
		//qDebug() << query.record().count();
		return query;
	}
	catch (...) {
		qDebug() << ("readDB  Failed Exception!");

	}
}


/**
* @brief Sqlite::writeDB,插入记录
* @param tb_name,数据表名
* @param columns,插入字符串,格式(字段值,字段值) 例:"ddd,abc"
* @return true/false
*/
bool DataBase::insertRecord(QString tbName, QString columnsValue)
{
	//1.validata
	assert(!tbName.isEmpty() && !columnsValue.isEmpty());

	//2.Insert
	try
	{
		QSqlQuery query(m_connInfo.db);
		QTime t;
		t.restart();

		QStringList parts = columnsValue.split(",");
		QString sql = "INSERT INTO " + tbName + " values (";
		for (int i = 0; i < parts.size(); i++) {
			sql.append("'" + parts[i] + "',");
		}
		QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

		sql.append("'" + time + "')");

		query.prepare(sql);
		bool success = query.exec();
		if (!success)
		{
			QSqlError lastError = query.lastError();
			qDebug() << lastError.driverText() << QStringLiteral("插入失败");
			return false;
		}
	}
	catch (...)
	{
		qDebug() << "DataBase::insertRow Exception!";
		return false;
	}
	return true;
}

bool DataBase::insertRecord(QString tbName, QString columns, QString columnsValue)
{
	//1.validata
	assert(!tbName.isEmpty() && !columnsValue.isEmpty() && !columns.isEmpty());

	//2.Insert
	try
	{
		QSqlQuery query(m_connInfo.db);
		QTime t;
		t.restart();

		QStringList columnParts = columns.split(",");
		QStringList valueParts = columnsValue.split(",");
		
		if (columnParts.count()!= valueParts.count())
		{
			qDebug() <<  QStringLiteral("sql error,value count not equal");
			return false;
		}
		//make columns
		QString strSqlColumn = " ( ";
		for (int i = 0; i < columnParts.size(); i++) {
			strSqlColumn.append(columnParts[i] + ",");
		}
		strSqlColumn.append("last_time");
		strSqlColumn.append(" )");
		
		//make columnsValues 
		
		QString sql = "INSERT INTO " + tbName + strSqlColumn+" values (";
		for (int i = 0; i < valueParts.size(); i++) {
			sql.append("'" + valueParts[i] + "',");
		}
		QString time = QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss");

		sql.append("'" + time + "')");

		query.prepare(sql);
		bool success = query.exec();
		if (!success)
		{
			QSqlError lastError = query.lastError();
			qDebug() << lastError.driverText() << QStringLiteral("插入失败");
			return false;
		}
	}
	catch (...)
	{
		qDebug() << "DataBase::insertRow Exception!";
		return false;
	}
	return true;
}

bool DataBase::beginTransaction()
{
	return m_connInfo.db.driver()->beginTransaction();
}

bool DataBase::rollbackTransaction()
{
	return m_connInfo.db.driver()->rollbackTransaction();
}

bool DataBase::commitTransaction()
{
	return m_connInfo.db.driver()->commitTransaction();

}

bool DataBase::isExistTable(const QString &tbName)
{
	static QStringList szListTable = m_connInfo.db.tables();
	return (szListTable.indexOf(tbName) >= 0);

}

bool DataBase::execSQL(const QString &sql, OUT QList<QStringList> &result)
{
	bool ret = true;
	QSqlQuery query(m_connInfo.db);
	result.clear();

	try {
		qDebug() << (QString("exec DB sql:%1").arg(sql));
		if (!query.exec(sql)) {
	//		qDebug() << (QString("sql execute fail:(%1) sql:%2")
	//						.arg(query.lastError().text)
	//						.arg(sql));
			ret = false;
		}

		while (query.next()) {
			int nField = query.record().count();
			QStringList valueList;
			for (int i = 0; i < nField; ++i)
				valueList << query.record().value(i).toString();

			result.append(valueList);
		}
	}
	catch (...) {
		// 		LogError(QString("sql execute exception:(%1) sql:%2")
		// 			.arg(query.lastError().text())
		// 			.arg(sql));
		qDebug() << "DataBase::execSQL Exception!";
		ret = false;
	}
	return ret;
}

bool DataBase::execSQL(const QString &sql)
{
	QList<QStringList> result;
	return execSQL(sql, result);
}

QSqlDatabase  DataBase::getSqlDbObject() const
{
	return m_connInfo.db;
}




测试初始化如下:

SqlConnInfo info;
info.connName = "KarlConnect";
info.connType = SQLITE_DRIVE;
info.dbName = strProjectFullName;

m_DbOperate->initDb(info);
if (m_DbOperate->openDb() ) {
}

// ins->createTable(“t_System”, “addr varchar,station_num int”);
// ins->beginTransaction();
// ins->writeDB(“t_System”, “0x222str,12”);
// ins->writeDB(“t_System”, “str11,18”);
// ins->writeDB(“t_System”, “str13,18”);
// ins->writeDB(“t_System”, “str14,18”);
// ins->writeDB(“t_System”, “str15,18”);
//
// QSqlQuery query = ins->readDB(“t_System”, “station_num:18”);
// while (query.next())
// {
// qDebug() << query.value(“addr”).toString();
// }
//
// ins->commitTransaction();

注释掉的为之前测试的,修改了接口后没测试,类似这种结构测试就行。
这个类在一个项目中使用,没有问题,后在另一个项目中出现QSQLITE driver not loaded 问题。
解决如下:
Qt安装目录下的plugin的 sqldrivers 目录复制到 可执行文件 目录下
如:
D:\Qt\Qt5.9.3\5.9.3\msvc2015_64\plugins\sqldrivers
Qt 封装Sqlite类,及问题出现QSqlDatabase: QSQLITE driver not loaded 解决_第1张图片
猜测:Vs qt 插件问题。可以成功使用的项目是新的插件2.5.2 版本。还需拷贝的是旧版本的插件,2.0

你可能感兴趣的:(Qt,sqlite,数据库)