Important: Please read the Qt Code of Conduct -

QDatabase error

  • I dont know why, but i try to use a QDatabase for SQLite Queries. In an earlier Project everything went fine, but now i want to do a workaround to solve a problem from that earlier Project. Im trying to open and close the Database everytime if i do a Query. But i get an Error that the driver is not loaded and the database is not open. First i show my Code then the Error.

    #include <QStandardPaths>
    #include <QSqlQuery>
    #include <QSqlError>
    #include <QDir>
    #include <QDebug>
        //Init Create Tables
    void gdms::Database::instanceDb(const QString &name)
        QString appDataLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
        mDb = QSqlDatabase::addDatabase("QSQLITE", name);
        QDir dir(appDataLocation);
        if (!dir.exists())
        appDataLocation.append(QString(QDir::separator()) + "gdms.sqlite");
        if (!
            qDebug() << "Error open Database. " + mDb.lastError().text();
    void gdms::Database::closeDb(const QString &name)
        if (mDb.isOpen())
            mDb = QSqlDatabase();
    void gdms::Database::dbTables()
        QSqlQuery query;
        query.prepare("CREATE TABLE IF NOT EXISTS treeview (id INTEGER PRIMARY KEY, index INTEGER, name TEXT)");
        if (!query.exec())
            qDebug() << "An Error occured during init/create Tables. " + query.lastError().text();

    and this i get when i run the app

    QSqlQuery::prepare: database not open
    "An Error occured during init/create Tables. Driver not loaded Driver not loaded"
    QSqlQuery::prepare: database not open

    Anyone knows what i do wrong? i really cant find a way to fix it. I cant create the Table in the Databasefile

  • Just a guess:

    QSqlQuery q; uses the default database connection.
    As you have set a connection name, you do not have a default connection so you have to tell the query which database to use
    use QSqlQuery q(mDb); instead.

  • thanks. that helped me.

Log in to reply