Matin Lotfaliee
Matin Lotfaliee

Reputation: 1615

QSqlDatabase concurrent queries in different threads

I have written the below code in order to have concurrent queries.

QString databaseName = "DB-"+QThread::currentThread()->objectName();
QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL",databaseName);
db.setHostName("192.168.1.2");
db.setDatabaseName("Behroozi");
db.setUserName("root");
db.setPassword("password");
db.open();

QSqlQuery query(db);
query.prepare("select * from Person where chatID=:chatID");
query.bindValue(":chatID",chatID);
if(query.exec())
    return true;    

db.close();
QSqlDatabase::removeDatabase(databaseName);

The code creates a connection with unique name, opens it, make query, closes it and at last removes the connection.

The problem is, it has memory leakage. When I comment the code, it does not leak. What else should I do in order to prevent it?

Is it a safe code I have written?

If I copy db.close() and removeDatabase before return, it will print:

QSqlDatabasePrivate::removeDatabase: connection 'DB-ReplyThread-1' is still in use, all queries will cease to work.

Upvotes: 1

Views: 510

Answers (2)

evilruff
evilruff

Reputation: 4085

As you create new connection in each thread its perfectly fine from Qt point of view, queries objects related to connection should be removed, so simplest way to avoid this message is something like this:

 ....
do {
    QSqlQuery query(db);
    query.prepare("select * from Person        where chatID=:chatID");
    query.bindValue(":chatID",chatID);
    if(query.exec())
        break;    
} while (0);

db.close();

....    
  QSqlDatabase::removeDatabase(databaseName);

so just limit the scope of QSqlQuery then it gets destroyed before you close connection.

Upvotes: 2

maxik
maxik

Reputation: 1123

To quote the documentation:

Also, the connection must remain open while the query exists; otherwise, the behavior of QSqlQuery is undefined.

So your code has to handle the query before closing the database connection. That might be the noticed leakage of yours.


Also note that your database driver may not support concurrency. I read something about that somewhere but cannot recall at the moment.

Upvotes: 0

Related Questions