Important: Please read the Qt Code of Conduct -

Evaluating QSqlQuery accross different threads

  • Hi,

    My application uses the QtSqlite driver to interact with a database. The QT docs states that no database connection can be moved between threads. Because of this limitation I created a serializer to execute all the queries from a single thread. Then I notify other threads via the signal/slot system (or call a blocking function that waits until the scheduled query is executed succesfully) once the query is done. The serializer creates a local QSqlQuery object that is used to execute the query string. Once the execution is done I copy the QSqlQuery object to the designated thread which (and destroy the local copy before any other thread is able to access the copied QSqlQuery object) scheduled it, basically moving the executed QSqlQuery object to another thread you might say. However I have some memory leak issues, when the QSqlQuery object (the one that is copied from the serializer thread to its own thread) is destroyed the resources are not free'd. I checked the internal reference counter to see how many references there are when the particular query is destroyed and I can confirm this is a value of '1' when the QSqlQuery is being destroyed. I'm not sure why this could be a problem as the query is created in the same thread where I created my database connection. I'll hope someone can shed some light on this subject.

    Kind Regards,


  • Qt Champions 2019

    @Mike-Neuhaus Somehow this sounds complicated. Why should all these threads deal with QSqlQuery? Why don't you let one thread access the database and provide data (not QSqlQuery!) to all the other threads?

  • @jsulm This is indeed a solution, I could cache the results and give the other threads access to the cached results. However the serializer is an integration in an existing system, the current software is using QSqlQuery extensively that's the only reason why I want to remain using the QSqlQuery class.

  • Moderators

    Hi @Mike-Neuhaus,

    I suspect you'll need to delve into the internal details of QSqlQuery to figure out if what you're doing is possible. Subscribe to the Interest mailing list ( ) and ask there -- Qt engineers are active there.

  • Qt Champions 2017

    What you want depends heavily on the driver in use, whether or not the SQLite driver can be used from different threads, I can't say. But the problem isn't with the SQL query class itself, it's with the driver (and the QSqlDatabase that holds a reference to the driver).

  • Thanks for all the answers, I ended up posting it on the interest. For now I implemented the cached results solution.

Log in to reply