How to nicely remove a database
Solved
General and Desktop
-
From the docs:
[static] void QSqlDatabase::removeDatabase(const QString &connectionName) Removes the database connection connectionName from the list of database connections. Warning: There should be no open queries on the database connection when this function is called, otherwise a resource leak will occur.
In my code I create a default connection to a database:
QSqlDatabase db = QSqlDatabase::addDatabase("QSQLITE"); db.setDatabaseName("db.sqlite"); db.open();
then in several functions I use queries, for example:
void DatabaseManager::addListItem(QString table, QString name) { QSqlQuery query; query.prepare("INSERT INTO " + table + " (name) values(?)"); query.addBindValue(name); query.exec(); }
when I'm done I want to remove the database connection:
QSqlDatabase db = QSqlDatabase::database(); db.close(); QSqlDatabase::removeDatabase(db.connectionName());
But I still receive the warning:
QSqlDatabasePrivate::removeDatabase: connection 'qt_sql_default_connection' is still in use, all queries will cease to work.
I don't understand why. The close method should free anything:
Closes the database connection, freeing any resources acquired, and invalidating any existing QSqlQuery objects that are used with the database.
Furthermore, because my queries are declared in different functions, the
QSqlQuery
object should be destroyed when exiting from the functions.Where's my mistake?
-
You must have a QSqlQuery somewhere around which is still using the connection. Maybe a QSqlTableModel or a QSqlQuery as a member variable.
-
That’s because you have an active QSqlDatabase object which is db.
See the removeDatabase documentation for the technique to use.
-
@Thank-You It's in the documentation I linked to.