I am trying to connect to an existing SQLlite database file in my qt 5.2 project(in Android OS). Where should i save this file to load it using this code:QSqlDatabase::addDatabase("myfile.sqlite");
?
First you should add a database connection using addDatabase with the driver type of QSQLITE and a connection name like MyConnection.
QSqlDatabase db = QSqlDatabase::addDatabase( "QSQLITE","MyConnection" );
Next you should Set the connection's database name and open it.
db.setDatabaseName( "myfile.sqlite" );
if( !db.open() )
{
QMessageBox::warning(this, tr("Failed to connect!"), tr("Error connecting to database: ")+db.lastError().driverText() );
}
Within your development folder you'll find \android\assets - just put the SQLite database file into that folder and add these to your .pro :
deployment.files += myfile.sqlite
deployment.path = /assets
INSTALLS += deployment
But the files in assets are readonly. So you should first copy it to some other location:
QFile dfile("assets:/myfile.sqlite");
if (dfile.exists())
{
dfile.copy("./myfile.sqlite");
QFile::setPermissions("./myfile.sqlite",QFile::WriteOwner | QFile::ReadOwner);
}
Now you can connect to your database as mentioned above.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With