我是C++/Qt的新手,我正在尝试写入我在项目根目录中创建的SQLite数据库。
以下是我一直在参考的许多站点中的一个:http://www.java2s.com/Code/Cpp/Qt/ConnecttoSqliteanddoinsertdeleteupdateandselect.htm
我创建了一个函数,该函数接收作为对象输入的所有用户的参数。我想将用户输入的这些值写入我的根目录数据库。
下面是接受数据库对象并尝试将它们写入根级数据库"matrixics.db“的函数。
My函数:
#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。
发布于 2015-03-15 14:39:25
您的QSqlQuery对象必须通过引用QSqlDatabase来构造。换句话说,把这句话说出来
QSqlQuery qry(matrixics);见 documentation。
https://stackoverflow.com/questions/29061546
复制相似问题