gpt4 book ai didi

c++ - 使用qt连接到SQLite数据库

转载 作者:行者123 更新时间:2023-11-30 01:08:27 25 4
gpt4 key购买 nike

我无法使用我的 qt 应用程序连接到我的 sqlite 数据库。我有一个帮助程序类 DBManager,它应该具有打开和关闭数据库的功能,因为我想在多个地方重用代码。这是 dbmanager.cpp

DBManager::DBManager()
{

}
void DBManager::connOpen()
{

path = QCoreApplication::applicationDirPath() + "/GameSuitedb.db";
mydb=QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName(path);

void DBManager::connClose() /*Closes connection and commits changes to database*/
{
mydb.close();
mydb.removeDatabase(QSqlDatabase::defaultConnection);
}

请注意,我的数据库名为 GameSuitedb,位于可执行文件旁边这是我试图访问我的数据库的地方:

void CreateUser::on_pushButton_submit_clicked()
{
dbmanager.connOpen();
QString username = ui->lineEdit_username->text();
QString password = ui->lineEdit_password->text(); //Gets password text
QSqlQuery qry(dbmanager.mydb);
qry.prepare("INSERT INTO users (username,password) VALUES ('"+username+"', '"+password+"')");

if(qry.exec()){
}
else{
ui->statusbar->showMessage(qry.lastError().text());
}
dbmanager.connClose();
}

上面的代码在启动时给我的错误是 QSqlQuery::prepare: database not open.

最佳答案

错误代码告诉您数据库未打开,因为您的 DBManager::connOpen() 函数似乎正在执行除了实际打开数据库之外的所有操作,这与它的命名方式相反。

您需要调用QSqlDatabase::open()DBManager::connOpen() 函数的末尾打开数据库并准备好使用。

void DBManager::connOpen()
{
path = QCoreApplication::applicationDirPath() + "/GameSuitedb.db";
mydb=QSqlDatabase::addDatabase("QSQLITE");
mydb.setDatabaseName(path);
if(!mydb.open())
{
//use lastError() here to figure out what went wrong.
}
}

关于c++ - 使用qt连接到SQLite数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42683579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com