As many of you are probably aware, Qt docs are quite clear about instances of QSqlDatabase and threads:

A connection can only be used from within the thread that created it. Moving connections between threads or creating queries from a different thread is not supported.
After migrating from raw MySQL libraries to a QSql-based approach, my application started behaving oddly. Evidently the raw MySQL does not have the cited constraint: my application indeed uses exactly two threads: the main thread, and a thread that receives sensor data. Under the current implementation, both threads do work with the database.

The following illustrates the current solution to the problem, which takes a lazy-loading approach. Everything appears to work, but I would welcome any and all constructive criticism.

Qt Code:
  1. // Controller.h
  3. private:
  4. CustomDatabase * databaseConnectionForThread(const Qt::HANDLE threadID = QThread::currentThreadId());
  6. QHash<Qt::HANDLE, CustomDatabase *> dbConnectionsByThread;
  7. QMutex threadMutex, sqlMutex;
To copy to clipboard, switch view to plain text mode 

Qt Code:
  1. // Controller.cpp
  3. CustomDatabase * Controller::databaseConnectionForThread(const Qt::HANDLE threadID) {
  4. QMutexLocker locker(&threadMutex);
  5. static int numberForConnectionName = 0;
  6. CustomDatabase *dbConnection;
  7. if (dbConnectionsByThread.contains(threadID))
  8. dbConnection = dbConnectionsByThread.value(threadID);
  9. else {
  10. dbConnection = CustomDatabase::create(QString::number(++numberForConnectionName), this); // create() initializes and opens the connection it returns
  11. if (!dbConnection->isOpen())
  12. exitWithError(QString("Controller::databaseConnectionForThread() - Failed: %1!").arg(dbConnection->lastError()));
  13. dbConnectionsByThread.insert(threadID, dbConnection);
  14. }
  15. return dbConnection;
  16. }
  18. void Controller::doStuffWithDatabase() {
  19. QMutexLocker locker(&sqlMutex);
  20. CustomDatabase *dbConnection = databaseConnectionForThread();
  21. // do stuff
  22. }
To copy to clipboard, switch view to plain text mode 

Thank you very much for your time.