SQL connections on multiple threads in a Qt application
How can I create and use multiple SQL db connections on different threads in a Qt application?
I have read the documentation which says
The connection can only be used from the thread that created it.
How can I separate connections on different threads?
You need to create a database connection for each thread. Use QSqlDatabase::addDatabase()
with different named connections as parameters in each thread to instantiate QSqlDatabase
. A static function addDatabase
is thread safe and can be called on different threads.
How can I create and use multiple sql db connections on different threads in a 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 are:
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 a memory connection at thread1 and a file connection at thread2. the only thing to do is get the data into the gui stream if it is a gui app
Follow this VoidRealms @youtube tutorial. It has a very good explanation on sql hookups, models and many other things about Qt.
If you still need more help after browsing, I'd love to send you a sample code to test.