How To Read An Existing Sqlite Database In Android Using Qt?
Solution 1:
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
.
Post a Comment for "How To Read An Existing Sqlite Database In Android Using Qt?"