PDA

View Full Version : UI use QSqltablemodel, the other thread use QSqlQuery to insert , return false



5free
3rd May 2015, 13:41
Hi,

I am struggling with the multi-thread QSQLITE, the GUI thread is refresh the display through QSqlTableModel, the other thread insert data to sqlite cyclically.
but the problem is, once GUI thread use QSqlTableModel::select(), the other thread could not insert , and return : QSqlError("5", "Unable to fetch row", "database is locked")

what could I do next step to resolve the problem?

my codes like below:

this is the GUI thread


processDisplayDB =new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE","processDisplaydb"));
processDisplayDB->setDatabaseName("databases/ProductionData.s3db");
if(!processDisplayDB->open()){
qDebug()<<"Could not open file!"<<endl;
return;
}else{
qDebug()<<"Open file: "<<processDisplayDB->databaseName()<<" sucessfully!"<<endl;
}
modelProcessDisplay = new QSqlTableModel(ui->tableViewProcessDisplay,*processDisplayDB);
modelProcessDisplay->setTable("processtable");


and through a timer to refresh the display

connect(&cylicTimerProcessDisplay,&QTimer::timeout,this,&MainWindow::processDisplayUpdate_cylic);

void MainWindow::processDisplayUpdate_cylic()
{
modelProcessDisplay->select();
}

the other thread is like this

processDB = new QSqlDatabase(QSqlDatabase::addDatabase("QSQLITE","processDB"));
processDB->setDatabaseName("databases/ProductionData.s3db");
if(!processDB->open()){
qDebug()<<"Could not open file!"<<endl;
return;
}else{
qDebug()<<"Open file: "<<processDB->databaseName()<<" sucessfully!"<<endl;
}
and write data cyclic

QSqlQuery query(*processDB);
qDebug()<<"insert processtable prepare : "
<<query.prepare("INSERT INTO processtable(SerialNo) "
"VALUES(:SerialNo)");
query.bindValue(":SerialNo",currentSerialNo);
qDebug()<<"insert processtable: "<<query.exec();

but the query.exec() return false, once the GUI thread excuted the select(), the return error is : QSqlError("5", "Unable to fetch row", "database is locked")

ChrisW67
3rd May 2015, 21:38
...and the error returned to the inserting code?
Ensure the insert code is wrapped in a transaction() that is finished with either commit() or rollback()