【QT小作】封装一个基本的操作sqlite的类
以下是一个简单的封装了基本操作SQLite的Qt类示例代码:
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QVariant>
#include <QDebug>
class SqliteHelper {
public:
SqliteHelper(const QString &dbName) {
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbName);
if (!db.open()) {
qDebug() << "数据库打开失败!";
}
}
~SqliteHelper() {
db.close();
}
bool executeQuery(const QString &query) {
QSqlQuery sqlQuery(db);
if (!sqlQuery.exec(query)) {
qDebug() << "执行SQL失败:" << query << "\n错误信息:" << sqlQuery.lastError();
return false;
}
return true;
}
QSqlQuery getQuery(const QString &query) {
QSqlQuery sqlQuery(db);
sqlQuery.exec(query);
return sqlQuery;
}
bool insert(const QString &table, const QMap<QString, QVariant> &data) {
QString columns;
QString values;
for (auto it = data.begin(); it != data.end(); ++it) {
columns += it == data.begin() ? it.key() : "," + it.key();
values += it == data.begin() ? ":" + it.key() : "," ":" + it.key();
}
QString query = QString("INSERT INTO %1 (%2) VALUES (%3)")
.arg(table)
.arg(columns)
.arg(values);
QSqlQuery sqlQuery = getQuery(query);
for (auto it = data.begin(); it != data.end(); ++it) {
sqlQuery.bindValue(":" + it.key(), it.value());
}
if (!sqlQuery.exec()) {
qDebug() << "插入数据失败:" << sqlQuery.lastError();
return false;
}
return true;
}
bool update(const QString &table, const QMap<QString, QVariant> &data, const QString &condition) {
QString sets;
for (auto it = data.begin(); it != data.end(); ++it) {
sets += it == data.begin() ? it.key() + " = :" + it.key() : "," + it.key() + " = :" + it.key();
}
QString query = QString("UPDATE %1 SET %2 WHERE %3").arg(table).arg(sets).arg(condition);
QSqlQuery sqlQuery = getQuery(query);
for (auto it = data.begin(); it != data.end(); ++it) {
sqlQuery.bindValue(":" + it.key(), it.value());
}
if (!sqlQuery.exec()) {
qDebug() << "更新数据失败:" << sqlQuery.lastError();
return false;
}
评论已关闭