Tuesday, March 24, 2009

QSqlDatabase closing problem while using QSqlTableModel with QTableView

Problem:

I was working on a application that deals with multiple databases when I encountered a problem while closing a connection. Even if I close the connection it seemed to be active and hence was not letting itself to be copied.
The code I used typically was :

QSqlDatabase db(Conn);

....................................
....................................

....................................
db.close();



The copying problem caused due to the connection remaining active got solved after enclosing the queries in proper scope. eg.

{
QSqlDatabase db = QSqlDatabase::database("sales");
QSqlQuery query("SELECT NAME, DOB FROM EMPLOYEES", db);
}
// Both "db" and "query" are destroyed because they are out of scope
QSqlDatabase::removeDatabase("sales"); // correct

But the problem reappeared, after I implemented a QTableView with a QSqlTableModel:

QSqlTableModel *model =new QSqlTableModel(this, Conn) ;
model->setTable("student");
model->setFilter("student_id=" +QString::number(Cmn_Global::student_id ));
model->setSort(3, Qt::AscendingOrder);
model->setEditStrategy(QSqlTableModel:: OnFieldChange);
model->select();
............................
...........................
ui.tableView->setModel(model);//view is the QTableView object

Calling db.close() failed to close the connection as the real time querying between the Model and the View, which was not possible for me to enclose within scope.


Solution:
The only solution that emerged was to kill the connection manually, by deleting the QSqlTableModel pointer related to the view using the following code:
QSqlTableModel* model= dynamic_cast (ui.tableView->model());
delete model;

And then calling the close method on the database.

The database can then be smoothly copied as the connection was no more active.

No comments:

Post a Comment