Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Qt how connect to an existing SQLlite file in android OS?

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");?

like image 843
Vadimcg Avatar asked Mar 20 '23 17:03

Vadimcg


1 Answers

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.

like image 152
Nejat Avatar answered Apr 02 '23 16:04

Nejat