Reputation: 43140
class Worker : public QThread
{
Q_OBJECT
public:
Worker()
{
// Here?
QSqlDatabase::addDatabase("QSQLITE", "connectionName");
...
}
void Worker::run()
{
// Or here?
QSqlDatabase::addDatabase("QSQLITE", "connectionName");
...
}
...
};
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.
Upvotes: 1
Views: 241
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