Database with multiple thread
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
Code:
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:
Code:
void *a(void *arg)
{
db.setDatabaseName("abc");
db.setHostName("127.0.0.1");
db.setUserName("root");
db.setPassword("123456");
db.open();
while(1)
{
printf("In Thd1\n");
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 :
Code:
void *b(void *arg)
{
db1.setDatabaseName("abc");
db1.setHostName("127.0.0.1");
db1.setUserName("root");
db1.setPassword("123456");
db1.open();
while(1)
{
printf("In Thd2\n");
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?
Re: Database with multiple thread
First : QSqlDatabase::open returns bool value - test it.
Second : if open() == false use QSqlDatabase::lastError() to check what is wrong.
Re: Database with multiple thread
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.
Re: Database with multiple thread
Thank You,
It's working fine.
I have added database handler to QSqlQuery.