Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/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");
    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?


  • Qt Champions 2019

    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.


Log in to reply