QSqlDatbase在查询完成之前关闭

时间:2014-06-18 08:03:50

标签: c++ qt

我正在尝试为我的应用程序实现一个数据库对象,但当我开始使用多个连接时,它变成了一场噩梦。下面,您可以看到我的database 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";
}

问题发生在另一个类(使用database):

databaseAdaptor::databaseAdaptor() {
    this->db = database();
    // other construction operations    
}
void databaseAdaptor::fetch() {
    QSqlQuery q = db.query("SELECT * FROM `activities`");
    qDebug() << "Rows count: " << q.numRowsAffected();
}

过去它有一些版本,但出于某种原因,现在qDebug()的输出是

Rows count: -1 // and it should be 2 for my current version of database.

Qt Documentation 中,据说这个班级&#39;成员是线程安全的。这可能是问题吗?我的意思是,线程可以在查询完成执行之前结束吗?

如果是这样,在所有查询完成执行之前,如何保持连接处于打开状态?

(我知道这很重要,但我相信其他人可能会在某些时候遇到这个问题,所以请花点时间阅读)。谢谢!

0 个答案:

没有答案