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?
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?