Find what is using a `QSqlDatabase` connection
-
Here my code:
Orders::Orders(QObject *parent) : QObject{parent} { QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL", "orders"); db.setHostName("localhost"); db.setDatabaseName("database"); db.setUserName("user"); db.setPassword("password"); db.setConnectOptions("MYSQL_OPT_RECONNECT=TRUE;"); _isConnected = db.open(); if (_isConnected) { _model = new QSqlTableModel(this, db); _model->setTable("orders"); _model->setEditStrategy(QSqlTableModel::OnManualSubmit); _model->select(); } } Orders::~Orders() { if (_model) _model->clear(); QSqlDatabase db = QSqlDatabase::database("orders"); db.close(); QSqlDatabase::removeDatabase("orders"); }
I don't have any
QSqlDatabase
norQSqlQuery
class member. I always create them inside the functions, example:void Orders::setOrderState(QString machine, QString id, DbOrderStates state) { QSqlDatabase db = QSqlDatabase::database("orders"); QString sql = QString("UPDATE orders SET states_id=:state WHERE id=:id AND machine=:machine"); QSqlQuery query(db); query.prepare(sql); query.bindValue(":state", static_cast<int>(state)); query.bindValue(":id", id); query.bindValue(":machine", machine); query.exec(); }
Still, it complains when I close the application:
QSqlDatabasePrivate::removeDatabase: connection 'orders' is still in use, all queries will cease to work.
I can't understand what is still in use... is there a way to find out what is using the connection?
-
@Mark81
If you try a standalone program with justOrders::Orders()
&Orders::~Orders()
in it do you still get the message? My first thought is that you do have aQSqlQuery
or similar left lying around somewhere.Hang on! I think it is your
Orders::~Orders()
which is the issue. You cannotQSqlDatabase::removeDatabase("orders")
in the same scope asQSqlDatabase db = QSqlDatabase::database("orders");
. You need:{ QSqlDatabase db = QSqlDatabase::database("orders"); db.close(); } QSqlDatabase::removeDatabase("orders");
This is even shown in https://doc.qt.io/qt-6/qsqldatabase.html#removeDatabase.
-
@JonB I read that paragraph dozen of times but I didn't realize the braces are intended to be literal! I understood it's just to point out I need to place the variables inside a function!
Anyway it still wasn't enough!
I had to add:delete _model;
even if the docs says:
Clears the model and releases any acquired resource.
-
-
-