3

How can I create and use several connections to a SQL db in different threads in a Qt application?

I've read the documentation which says

A connection can only be used from within the thread that created it.

How can I separate connections in different threads?

Nejat
  • 31,784
  • 12
  • 106
  • 138
Hardwired
  • 804
  • 1
  • 8
  • 19

3 Answers3

6

You should create a database connection per thread. Use QSqlDatabase::addDatabase() with different connection names as parameters in each thread to create instances of QSqlDatabase. The static addDatabase function is thread safe and could be called in different threads.

Nejat
  • 31,784
  • 12
  • 106
  • 138
2

How can I create and use several connection to sql db in a different threads in the program using Qt?

// general worker init slot
DbWorker::init()
{
    this->db = QSqlDatabase::addDatabase("QSQLITE", dbName);
    db.setDatabaseName(dbPath);
    db.open();
}

when in your main class or wherever you have something like:

DbWorker w1 = new DbWorker;
w1.setDbName("mem_db");
w1.setDbPath(":memory:");
QThread* t1 = new QThread(this);
w1->moveToThread(t1);
connect(t1, SIGNAL(started()), w1, SLOT(init()));
t1->start();

DbWorker w2 = new DbWorker;
w1.setDbName("file_db");
w1.setDbPath("~/usr/foo.db");
QThread* t2 = new QThread(this);
w1->moveToThread(t1);
connect(t2, SIGNAL(started()), w2, SLOT(init()));
t1->start();

so you have your memory connection in thread1 and the file connection in thread2. the only thing to manage is to fetch data to the gui thread if it is a gui application

Zaiborg
  • 2,492
  • 19
  • 28
  • yes, this is Gui app (gui thread that read from DB and working thread, that read and write to DB.) Now I'm using only one connection for two thread and sometimes happens that query read data from GUI thread is in query result of working thread (corrupted or not valid). thanks! – Hardwired Apr 21 '15 at 10:42
  • be aware that `non gui threads` are not allowed to access the gui elements. share your data with `signals/slots` and you should be good to go – Zaiborg Apr 21 '15 at 11:13
-2

Follow this tutorial from VoidRealms @ youtube. He has a very good explanation on sql connection,models and many other stuff about Qt.

If you still need more help after watching it, it would be my pleasure to send you a sample code for you to test it.

Armando
  • 309
  • 1
  • 4
  • 10
  • 1
    Spent 10 minutes watching the whole video. Did not cover multithreaded scenarios at all. Just contains the very basics of setting up a connection using Qt. – Evan Jun 14 '16 at 15:04