Close and reopen connection to database
I have a 'small but long' task. On a user request, the query to database should happen, this query can run for some noticeable time.
So this task is moved to a thread with a run() like this:
Code:
void SubTask::run() {
if (!db2.open()) {
err = "Failed to open db connection" + connName;
qCritical() << err;
}
qry.exec( .... );
qry,clear();
db2.close();
}
It works fine, query is executing each time user requests it.
But in the console I have a warning:
Code:
QSqlDatabasePrivate::removeDatabase: connection '140551504512768' is still in use, all queries will cease to work.
One such warning for each execution.
What am I doing wrong? How the connection should be closed correctly?
Re: Close and reopen connection to database
Quote:
What am I doing wrong? How the connection should be closed correctly?
You may not need the call to QSqlDatabase::removeDatabase(). The clone (db2) will go out of scope when run() exits, thus closing the connection. See the examples and discussion under removeDatabase(). However, if it turns out you do need it, then you can put lines 3 - 11 inside of their own scope ("{}") and avoid the warning.
Re: Close and reopen connection to database
Quote:
Originally Posted by
d_stranz
Actually - no.
I am not sure about the mechanics of the process, but if the name of the secondary connection is a constant, then there are warnings about "such connection already exists, closing old one". Even though that connection belonged to a thread which was ended hours ago.
That was the reason why the connection name was renamed from a constant to a thread number. It masked the problem of existing connection and produced a leak. Which we were looking for for years...
Quote:
Originally Posted by
d_stranz
See the examples and discussion under removeDatabase(). However, if it turns out you do need it, then you can put lines 3 - 11 inside of their own scope ("{}") and avoid the warning.
Strangely, but yes, that actually solved all the problems. Adding another layer of visibility - did a trick of completely disposing of a secondary connection.
So the actual answer to main question of this topic:
The db2 object should be destroyed before calling QSqlDatabase::removeDatabase(). The destruction can either be by manually calling the destructor or by the object going out of visibility scope and calling the destructor that way.
Re: Close and reopen connection to database
Quote:
Originally Posted by
White_Owl
The db2 object should be destroyed before calling QSqlDatabase::removeDatabase(). The destruction can either be by manually calling the destructor or by the object going out of visibility scope and calling the destructor that way.
Correct, properly documented in the QSqlDatabase::removeDatabase() documentation :)