这是我的databaseconnection.h类
#ifndef DATABASECONNECTION_H
#define DATABASECONNECTION_H
#include <QtSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
class DatabaseConnection
{
public:
DatabaseConnection();
bool dbConOpen();
void dbConClose();
QSqlDatabase db;
};
#endif // DATABASECONNECTION_H
databaseconnection.cpp
#include <QtSql>
#include <QtSql/QSqlDatabase>
#include <QtSql/QSqlDriver>
#include <QtSql/QSqlQuery>
#include <QDebug>
#include "databaseconnection.h"
DatabaseConnection::DatabaseConnection()
{
}
bool DatabaseConnection :: dbConOpen()
{
db = QSqlDatabase ::addDatabase("QMYSQL");
db.setHostName("localhost");
db.setDatabaseName("lms");
db.setUserName("root");
db.setPassword("");
if(!db.open())
{
return false;
}
else
return true;
}
void DatabaseConnection :: dbConClose()
{
QString connection = db.connectionName();
db.close();
db = QSqlDatabase();
db.removeDatabase(connection);
}
fictionsection类通过materials.h类继承数据库类。然后我通过点击fictionsection.cpp类中的按钮将表记录加载到qtableview,如下所示
void FictionSection::on_btnLoad_clicked()
{
DatabaseConnection mydb;
mydb.dbConOpen();
//Loading fiction table values to a table
QSqlQueryModel *modl = new QSqlQueryModel();
QSqlQuery *query = new QSqlQuery(mydb.db) ;
query->prepare(" select * from fiction");
bool flag = query->exec();
//assigning the values to a QTableView
if(flag == true)
{
modl->setQuery(*query);
ui->tblFiction->setModel(modl);
ui->tblFiction->show();
}
dbConClose();
}
项目运行时,它会显示以下消息。但该项目完全符合我的要求。
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
QSqlDatabasePrivate::addDatabase: duplicate connection name 'qt_sql_default_connection', old connection removed.
请帮我解决这个问题,并且由于此消息有任何不良影响。因为我计划在完成整个实施后在Ubuntu中运行我的项目。目前我使用的是Windows操作系统。
答案 0 :(得分:0)
由于不必要地打开和关闭数据库连接,显示此消息。最终代码应如下所示。
void FictionSection::on_btnLoad_clicked()
{
DatabaseConnection mydb;
//Loading fiction table values to a table
QSqlQueryModel *modl = new QSqlQueryModel();
QSqlQuery *query = new QSqlQuery(mydb.db) ;
query->prepare(" select * from fiction");
bool flag = query->exec();
//assigning the values to a QTableView
if(flag == true)
{
modl->setQuery(*query);
ui->tblFiction->setModel(modl);
ui->tblFiction->show();
}
}