Search code examples
qtsqliteqsqlqueryqsqldatabase

Qt Threads and the default QSQLDatabase connection (sqlite)


Is it safe to use default database connection from different threads? Like this:

bool upSafe(const QString &mig_to, const QString &mig_from) const {
  if (!QSqlDatabase::database().transaction()) {
    qCCritical(hfCoreMT) << "Failed init database transaction";
    return false;
  }

  if (!up(mig_to, mig_from)) {
    QSqlDatabase::database().rollback();
    return false;
  }

  return QSqlDatabase::database().commit();
}

In function up default QSQLQuery created and executed. Maybe some hints to the right pattern?


Solution

  • QSqlDatabase (which represents one DB connection) is not reentrant. You can use a connection only from the thread you created it. If you need to perform queries from another thread you need to create another connection from that thread first.