Copy tables between sqlite databases, qt, causes error
我想在用户单击时将我的 SQlite 数据库的内容写入另一个 SQlite 数据库。为此,我试图连接到两个数据库并从一个数据库中选择查询,并在事务中向另一个数据库插入查询。但是我在连接创建本身时遇到错误。
在头文件中:
1 2 3 | private: QSqlDatabase database; QSqlDatabase mHistoryDB; |
在源文件中:
1 2 3 4 5 6 7 8 9 10 | qDebug() << Q_FUNC_INFO <<"Invoked"; database = QSqlDatabase::addDatabase("QSQLITE"); mHistoryDB = QSqlDatabase::addDatabase("QSQLITE"); #ifdef Q_OS_WIN database.setDatabaseName("C:/ANDROID_DATABASE/RestPos.sqlite"); mHistoryDB.setDatabaseName("C:/ANDROID_DATABASE/History/RestPos.sqlite"); #else database.setDatabaseName("/mnt/sdcard/pos/RestPos.sqlite"); mHistoryDB.setDatabaseName("/mnt/sdcard/pos/History/RestPos.sqlite"); #endif |
运行时出现以下错误:
QSqlDatabasePrivate::removeDatabase: 连接\\'qt_sql_default_connection\\'仍在使用中,所有查询都将停止工作。
QSqlDatabasePrivate::addDatabase: 重复连接名称\\'qt_sql_default_connection\\',旧连接已删除。
如果我只使用数据库连接,则不会出现错误。我不确定如何使用单个连接进行复制。
我目前的复制代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | bool readStatus = false, writeStatus = false; if (database.isOpen() && mHistoryDB.open()) { QSqlQuery readQuery (database); QSqlQuery writeQuery(mHistoryDB); readStatus = readQuery.exec("SELECT costcentre_id, bill_no, bill_date" "FROM BillHdr"); qDebug() << Q_FUNC_INFO << getLastExecutedQuery(readQuery); if (readStatus) { mHistoryDB.transaction(); writeQuery.prepare("INSERT INTO BillHdr" "(costcentre_id, bill_no, bill_date)" "VALUES (:costcentre_id, :bill_no, :bill_date)"); while(readQuery.next()) { if (readQuery.isValid()) { BillHeader billHdr; billHdr.costCenterId = readQuery.value(0).toString(); billHdr.billNumber = readQuery.value(1).toDouble(); billHdr.date = readQuery.value(2).toDate(); writeQuery.bindValue(":costcentre_id", billHdr.costCenterId); writeQuery.bindValue(":bill_no", billHdr.billNumber); writeQuery.bindValue(":bill_date", billHdr.date); writeStatus = writeQuery.exec(); qDebug() << Q_FUNC_INFO << getLastExecutedQuery(writeQuery); if (!writeStatus) { qDebug() << Q_FUNC_INFO <<"error in write" << writeQuery.lastError().text(); mHistoryDB.rollback(); mHistoryDB.close(); break; } } } writeStatus = mHistoryDB.commit(); qDebug() << Q_FUNC_INFO <<"commit:" << writeStatus; if (!writeStatus) { mHistoryDB.rollback(); } mHistoryDB.close(); } } qDebug() << Q_FUNC_INFO <<"Exits" << writeStatus; return writeStatus; |
我们可以从 Qt 文档中了解
Warning: If you add a connection with the same name as an existing connection, the new connection replaces the old one. If you call this
function more than once without specifying connectionName, the default
connection will be the one replaced.
因此,当您以特定名称或未指定任何(默认连接)多次添加数据库时,连接将被替换并出现该警告。
您应该为每个具有不同连接名称的数据库调用一次
1 2 | database = QSqlDatabase::addDatabase("QSQLITE","database_Connection"); mHistoryDB = QSqlDatabase::addDatabase("QSQLITE","mHistoryDB_Connection"); |