Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

SQLite adding Table query fails



  • I have the following code:

        auto db = QSqlDatabase::addDatabase("QSQLITE", "Connection");
        db.setDatabaseName("test.db");
        if (!db.open()) {
            qDebug("Error occurred opening the database.");
            qDebug("%s.", qPrintable(db.lastError().text()));
            return;
        }
    
        if(!db.isDriverAvailable("QSQLITE"))
        {
            qDebug("Driver not available");
            return;
        }
    
        // Insert table.
        QSqlQuery query(db);
        qDebug() << query.prepare("CREATE TABLE IF NOT EXISTS test (id INTEGER PRIMARY KEY, text TEXT)");
        if (!query.exec()) {
            qDebug("Error occurred creating table.");
            qDebug() << db.lastError().text();
            return;
        }
    

    When I try to insert a table the query fails and this part is excuted:

        if (!query.exec()) {
            qDebug("Error occurred creating table.");
            qDebug() << db.lastError().text();
            return;
        }
    

    However theres no error code stating what went wrong. Console output is simply this:

    true
    Error occurred creating table.
    " "
    

    So what could be the reason for a query.excec() to fail?

    As a side note I run Qt under KDE Neon Linux. Could it be a OS issue?



  • I found the answer myself. In linux you have to store the database under home according to http://qt.shoutwiki.com/wiki/Creating_an_SQLite_database_in_Qt

    #ifdef Q_OS_LINUX
    // NOTE: We have to store database file into user home folder in Linux
    QString path(QDir::home().path());
    path.append(QDir::separator()).append("test.sqlite");
    path = QDir::toNativeSeparators(path);
    db.setDatabaseName(path);
    #else
    // NOTE: File exists in the application private folder, in Symbian Qt implementation
    db.setDatabaseName("test.sqlite");
    #endif
    

    That solved my issue now it works

    I wonder whats the reason.


  • Lifetime Qt Champion

    Hi,

    Your executable might be in a read-only folder and since you are using a relative path, it will try to create the file while it can not.

    A better solution is to use QStandardPaths::writableLocation so you can get a suitable folder cross-platform.



  • Thanks for the hint. I changed it like this

    QString path(QStandardPaths::writableLocation(
        QStandardPaths::StandardLocation::DesktopLocation));
    path.append(QDir::separator()).append("test.sqlite");
    path = QDir::toNativeSeparators(path);
    db.setDatabaseName(path);
    

    it seems to work


Log in to reply