How to read an existing SQLite database in Android using Qt?

前端 未结 1 992
半阙折子戏
半阙折子戏 2021-01-25 02:42

I have been developing an app in Qt on Ubuntu which works with an SQLite database and several GB of files. Everything is working well in Ubuntu and Windows, but... when I try t

相关标签:
1条回答
  • 2021-01-25 03:25

    Make sure the file exists

    As already mentioned in the comments, before calling

    db.setDatabaseName(dbName);
    

    make sure that dbName refers to an existing file in the filesystem. Because otherwise QSqlDatabase::open() will silently create an empty SQLite3 database by that name. You would then see an error like yours, or also "Parameter count mismatch" when attempting the first query.

    Or prevent open() from creating the file

    If you rather want QSqlDatabase::open() to fail if the specified database does not exist and only require read-only access, you can utilize a side effect of connection option QSQLITE_OPEN_READONLY (source):

    db.setConnectOptions("QSQLITE_OPEN_READONLY");
    db.setDatabaseName(dbName);
    if (!db.open()) {
        // ...
    }
    

    SQLite itself also has an option SQLITE_OPEN_READWRITE that would not restrict this solution to read-only access, but this option is not yet supported in the Qt interface.

    And only use ordinary filesystem filenames

    For reference, when calling QSqlDatabase::setDatabaseName() don't try to specify a file using the qrc:/ Qt resource scheme or assets:/ Qt-style Android assets access scheme. The method only accepts plain relative or absolute filesystem filenames (or their equivalent as SQLite-specific file: URIs). ((This is not mentioned in the documentation, but visible in the Qt source code here: Qt forwards the given filename to sqlite3_open_v2() and that only accepts filesystem filenames.))

    The only way to access a database bundled with the application into the Android APK package is to first copy it to the application's data directory. Because that copy then has has an ordinary filesystem path. of the form /data/data/com.example.appname/files/database.sqlite.

    0 讨论(0)
提交回复
热议问题