Important: Please read the Qt Code of Conduct -

How to nicely remove a database

  • 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");

    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(?)");

    when I'm done I want to remove the database connection:

    QSqlDatabase db = QSqlDatabase::database();

    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?

  • Lifetime Qt Champion

    You must have a QSqlQuery somewhere around which is still using the connection. Maybe a QSqlTableModel or a QSqlQuery as a member variable.

  • Lifetime Qt Champion

    That’s because you have an active QSqlDatabase object which is db.

    See the removeDatabase documentation for the technique to use.

  • @SGaist I saw that note, but I misunderstood it. Fixed now.

  • @Mark81 Then please share code with us

  • Lifetime Qt Champion

    @Thank-You It's in the documentation I linked to.

  • @SGaist Yes I got it

Log in to reply