#include <QCoreApplication>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QDebug>
void appendData(const QString& sourceDbPath, const QString& targetDbPath) {
// 打开源数据库
QSqlDatabase sourceDb = QSqlDatabase::addDatabase("QSQLITE", "source");
sourceDb.setDatabaseName(sourceDbPath);
if (!sourceDb.open()) {
qDebug() << "Failed to open source database:" << sourceDb.lastError().text();
return;
}
// 打开目标数据库
QSqlDatabase targetDb = QSqlDatabase::addDatabase("QSQLITE", "target");
targetDb.setDatabaseName(targetDbPath);
if (!targetDb.open()) {
qDebug() << "Failed to open target database:" << targetDb.lastError().text();
return;
}
// 从源数据库中读取数据
QSqlQuery selectQuery(sourceDb);
selectQuery.prepare("SELECT key, value FROM tabelName");
if (!selectQuery.exec()) {
qDebug() << "Failed to execute select query:" << selectQuery.lastError().text();
return;
}
// 开始事务
targetDb.transaction();
QSqlQuery insertQuery(targetDb);
insertQuery.prepare("INSERT INTO tabelName (key, value) VALUES (?, ?)");
while (selectQuery.next()) {
QString key = selectQuery.value(0).toString();
QByteArray value = selectQuery.value(1).toByteArray();
// 检查目标数据库中是否已经存在相同的 key
QSqlQuery checkQuery(targetDb);
checkQuery.prepare("SELECT COUNT(*) FROM tabelName WHERE key = ?");
checkQuery.addBindValue(key);
if (!checkQuery.exec()) {
qDebug() << "Failed to execute check query:" << checkQuery.lastError().text();
continue; // 如果查询失败,跳过该记录
}
checkQuery.next();
if (checkQuery.value(0).toInt() > 0) {
// 如果存在相同的 key,跳过插入
continue;
}
// 插入数据
insertQuery.addBindValue(key);
insertQuery.addBindValue(value);
if (!insertQuery.exec()) {
qDebug() << "Failed to insert data:" << insertQuery.lastError().text();
}
}
// 提交事务
targetDb.commit();
// 关闭数据库连接
sourceDb.close();
targetDb.close();
}
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
QString sourceDbPath = "source.db"; // 源数据库路径
QString targetDbPath = "target.db"; // 目标数据库路径
appendData(sourceDbPath, targetDbPath);
return a.exec();
}
Qt实现两个数据库合并操作
于 2024-08-31 14:09:39 首次发布