C++ QSqlDatbase在查询完成之前关闭

C++ QSqlDatbase在查询完成之前关闭,c++,qt,C++,Qt,我试图为我的应用程序实现一个数据库对象,但当我开始使用多个连接时,它变成了一场噩梦。下面,你可以看到我的数据库< /Cl> C++类代码: // here are the declarations QString server_addr; QString username; QString password; QString database_name; QSqlDatabase connection; QString error; QString connectionName; QSqlQue

我试图为我的应用程序实现一个数据库对象,但当我开始使用多个连接时,它变成了一场噩梦。下面,你可以看到我的<代码>数据库< /Cl> C++类代码:

// here are the declarations
QString server_addr;
QString username;
QString password;
QString database_name;
QSqlDatabase connection;
QString error;
QString connectionName;
QSqlQuery m_query;

// and here are the definitions
database::database(QString connectionName) {
    preferences p; p.read();

    QString iConnectionName = (connectionName == "") ? default_connection_name : connectionName;
    this->connectionName = iConnectionName;

    if (QSqlDatabase::contains(iConnectionName))
        this->connection = QSqlDatabase::database(iConnectionName);
    else this->connection = QSqlDatabase::addDatabase("QMYSQL", iConnectionName);

    this->connection.setHostName(p.database->server_addr);
    this->connection.setUserName(p.database->username);
    this->connection.setPassword(p.database->password);
    this->connection.setDatabaseName(p.database->database_name);
    this->connection.setPort(p.database->serverPort);

    if (!connection.open())
    {
        this->error = this->connection.lastError().text();
    }
    else this->error = "";
}
QSqlQuery database::query(QString query_text) {
    this->m_query = QSqlQuery(query_text, this->connection);
    this->m_query.exec();

    return m_query;
}
database::~database() {
    if (!this->m_query.isActive()) QSqlDatabase::removeDatabase(this->connectionName);
    qDebug() << "database object destroyed\n";
}
它在过去的一些版本中起作用,但由于某些原因,现在来自
qDebug()
的输出是

Rows count: -1 // and it should be 2 for my current version of database.
中,据说该类的成员是线程安全的。这可能是问题所在吗?我的意思是,线程能否在查询完成执行之前结束

如果是,我如何保持连接打开,直到所有查询完成执行?


(我知道要读的东西很多,但我相信其他人在某个时候可能会有这个问题,所以请慢慢看)。谢谢大家!

我在使用Qt运行MySQL时遇到了一个问题——它不受开箱即用的支持。出于测试目的,我建议将QMYSQL更改为QSQLITE,看看是否有效。如果是,您知道问题与MySQL驱动程序或db有关。如果不是,问题可能在于您的实现。你能改变MySQL数据库的内容吗?(如cmd line、direct connection或某些web应用)数据库不应该有任何问题,因为它;在localhost:3500databaseadapter:this->db=database();-这是多余的(最有可能的),因为您可以直接分配它,我假设this->db是一个正则变量,并且默认设置为“database()”(换句话说:调用default ctor)。可能默认的ctor(调用两次)没有正确连接到db?另外,您是否检查open是否成功(实际检查错误消息)?您是否阅读了我对
数据库
构造函数的定义?它将
error
变量设置为数据库的最后一个错误。我正在使用
qDebug()错误用于每个构造,但似乎没有错误。我在调试输出中得到了一些其他信息:
QSqlDatabasePrivate::removeDatabase:connection'WORKING\u DATABASE'仍在使用中,所有查询将停止工作。
Rows count: -1 // and it should be 2 for my current version of database.