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?

1
  • 1
    Create a connection in each thread that needs one? Commented Apr 21, 2015 at 8:19

3 Answers 3

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL", __func__);
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

2 Comments

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!
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
-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.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.