Qt 5.4,数据库未打开错误

Qt 5.4, database not open error

本文关键字:错误 数据库 Qt      更新时间:2023-10-16

我是C++/Qt的新手,正在尝试写入我在项目的根目录中创建的SQLite数据库。

以下是我一直使用的众多网站之一以供参考:http://www.java2s.com/Code/Cpp/Qt/ConnecttoSqliteanddoinsertdeleteupdateandselect.htm

我创建了一个函数,该函数接收所有用户输入的值作为对象的参数。我想将用户输入的这些值写入我的根目录数据库。

这是获取数据库对象并尝试将它们写入我的根级数据库"matrixics.db"的函数。

我的职能:

#include <QtSql>
#include <QSqlDatabase>
#include <QtDebug>
#include <QFile>
#include <QMessageBox> 
void db_connection::writeDBValues(db_config *dbInfo)
    {
        //connect to matrixics.db
        QSqlDatabase matrixics = QSqlDatabase::addDatabase("QSQLITE", "MatrixICS");
        //using absolute path doesn't work either            
        //matrixics.setDatabaseName("D:/Qt Projects/build-MatrixICS-Desktop_Qt_5_4_0_MinGW_32bit-Debug/matrixics.db");
        matrixics.setDatabaseName("./matrixics.db");
        if(!QFile::exists("./matrixics.db"))
        {
            QString failedMsg = tr("FAILED: Could not locate matrixics.db file");
            QMessageBox::warning(this, tr("ERROR: Failed MatrixICS Database Connection!"), failedMsg);
        }
        else if (!matrixics.open())
        {
            QString failedMsg = tr("FAILED: ") + matrixics.lastError().text();
            QMessageBox::warning(this, tr("ERROR: Failed to open matrixics.db!"), failedMsg);
        }
        else
        {
            //write db values
            QSqlQuery qry;
            if (m_connectionName == "localDb")
            {
                qry.prepare( "INSERT INTO settings (local_db_type, local_db_host, local_db_port, local_db_user, local_db_pass) VALUES (?, ?, ?, ?, ?)" );
            }
            else if (m_connectionName == "remoteDb")
            {
                qry.prepare( "INSERT INTO settings (remote_db_type, remote_db_host, remote_db_port, remote_db_user, remote_db_pass) VALUES (?, ?, ?, ?, ?)" );
            }
            //bind all values
            qry.addBindValue(dbInfo->m_db_type);
            qry.addBindValue(dbInfo->m_hostname);
            qry.addBindValue(dbInfo->m_port);
            qry.addBindValue(dbInfo->m_db_user);
            //encode user pass
            //base64_encode is included in a globals.h fn not shown above
            QString encodedPass = base64_encode(dbInfo->m_db_pass);
            qry.addBindValue(encodedPass);
            if(!qry.exec()) qDebug() << qry.lastError();
            matrixics.close();
        }
        QSqlDatabase::removeDatabase("MatrixICS");
    }

错误:

QSqlQuery::prepare: database not open
QSqlError("", "Driver not loaded", "Driver not loaded")
QSqlDatabasePrivate::removeDatabase: connection 'MatrixICS' is still in use, all queries will cease to work.

我的问题:

脚本如何在不打开数据库的情况下将其简化为QSqlQuery::prepare函数?我认为当我执行if (!matrixics.open())时,如果数据库未打开,脚本会抛出我的"无法打开"消息。但是,事实并非如此,因此逻辑应该规定数据库实际上是开放的,但我收到QSqlQuery::prepare: database not open.

您的QSqlQuery对象必须使用对QSqlDatabase的引用来构造。换句话说,使这条线

QSqlQuery qry(matrixics);

请参阅QSqlQuery::QSqlQuery文档。