PDA

View Full Version : Database with multiple thread



Surajkumar
9th June 2015, 10:10
Hi,
I want to access the database from 2 different threads and i am establishing the connection of database within the threads, but still when i access dartabase i get error as follows:
QSqlQuery::prepare: database not open

My code snippet is as follows:
In constructor i am starting the 2 threads


pthread_create(&hd1, NULL, a, NULL);
pthread_create(&hd2, NULL, b, NULL);
pthread_join(hd1,NULL);
pthread_join(hd2,NULL);

The below are Thread functions:

void *a(void *arg)
{
db = QSqlDatabase::addDatabase("QPSQL","con1");
db.setDatabaseName("abc");
db.setHostName("127.0.0.1");
db.setUserName("root");
db.setPassword("123456");
db.open();

while(1)
{
printf("In Thd1\n");
QSqlQuery qry2;
qry2.prepare("SELECT max(msgid) from tx_msg");
qry2.exec();
while(qry2.next())
{
printf("MSGID:%d",qry2.value(0).toInt()) ;
}
usleep(1000);
}
pthread_exit(NULL);
}

2nd thread :


void *b(void *arg)
{
db1 = QSqlDatabase::addDatabase("QPSQL","con2");
db1.setDatabaseName("abc");
db1.setHostName("127.0.0.1");
db1.setUserName("root");
db1.setPassword("123456");
db1.open();
while(1)
{
printf("In Thd2\n");
QSqlQuery qry1;
qry1.prepare("SELECT max(msgid) from tx_msg");
qry1.exec();
while(qry1.next())
{
printf("MSGID:%d",qry1.value(0).toInt()) ;
}
usleep(1000);
}
pthread_exit(NULL);
}


How can i access same database from different threads?

Lesiok
9th June 2015, 10:38
First : QSqlDatabase::open returns bool value - test it.
Second : if open() == false use QSqlDatabase::lastError() to check what is wrong.

wysota
9th June 2015, 11:40
QSqlQuery takes an argument of the database handler it is to operate on. If one is not given, it falls back to the default connection which obviously in your case is not open.

Surajkumar
9th June 2015, 13:45
Thank You,
It's working fine.
I have added database handler to QSqlQuery.