1

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.

1
  • How do you know it has memory leakage? Does memory usage increase under Process Explorer? Commented Jul 4, 2016 at 7:06

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.