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>
    
    gdms::Database::Database()
    {
        //Init Create Tables
        dbTables();
    
    }
    
    void gdms::Database::instanceDb(const QString &name)
    {
        QString appDataLocation = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);
        mDb = QSqlDatabase::addDatabase("QSQLITE", name);
        QDir dir(appDataLocation);
        if (!dir.exists())
            dir.mkpath(appDataLocation);
        appDataLocation.append(QString(QDir::separator()) + "gdms.sqlite");
        mDb.setDatabaseName(appDataLocation);
        if (!mDb.open())
            qDebug() << "Error open Database. " + mDb.lastError().text();
    }
    
    void gdms::Database::closeDb(const QString &name)
    {
        if (mDb.isOpen())
        {
            mDb.close();
            mDb = QSqlDatabase();
        }
        mDb.removeDatabase(name);
    }
    
    void gdms::Database::dbTables()
    {
        instanceDb("initdb");
    
        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();
    
        closeDb("initdb");
    }
    

    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
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.