Nick Dandoulakis
Nick Dandoulakis

Reputation: 43140

Should the thread be running when I create the connection?

class Worker : public QThread
{
    Q_OBJECT

public:
   Worker()
   {
      // Here?
      QSqlDatabase::addDatabase("QSQLITE", "connectionName");

      ...
   }

   void Worker::run()
   {
      // Or here?
      QSqlDatabase::addDatabase("QSQLITE", "connectionName");

      ...
   }

  ...
};

Threads and the SQL Module

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. In addition, the third party libraries used by the QSqlDrivers can impose further restrictions on using the SQL Module in a multithreaded program. Consult the manual of your database client for more information

I explored a bit the related Qt classes and I found no code that relates threads and database connections. It seems that Qt leaves that job to the database drivers, due to the Moving connections between threads or creating queries from a different thread is not supported.

What I believe is that, if we don't use simultaneously a connection from two threads, it doesn't matter where or when we create (and use) a connection.

  1. Should the thread be running when we add the connection?
  2. Do we actually must use a connection only from within the thread that created it?

Upvotes: 1

Views: 241

Answers (1)

Kamil Klimek
Kamil Klimek

Reputation: 13130

::run method is thread entry point. It will be executed in new thread. QThread constructor will be excuted in thread where QThread is initialized and started. So if you're going to use database object IN created thread, then you ensure that it will be called IN this new thread

Upvotes: 1

Related Questions