mehdihajatpour
mehdihajatpour

Reputation: 1

how to connecting to sqlite by qt and run it on android

I want to connect sqlite database and write an Android app.
but,when i run the app i give an error which said: database not open.

#include "csqlconnect.h"
#include <QFile>
#include <QSqlQuery>
#include <QMessageBox>
#include <QDebug>
#include <QSql>
#include <QSqlError>
#include <QSqlTableModel>
#include <QSqlRecord>

CSqlConnect::CSqlConnect()
{
db = QSqlDatabase::addDatabase( "QSQLITE","MyConnection" );
QFile dfile("./myfile.sqlite");
bool dbf=dfile.exists();
if (!dbf)
{
QFile::copy("assets:/myfile.sqlite", "./myfile.sqlite");
QFile::setPermissions("./myfile.sqlite",QFile::WriteOwner |    QFile::ReadOwner);
}
db.setDatabaseName( "myfile.sqlite" );
bool open=db.open();
if(!open)
{
QMessageBox::warning(0, "Failed to connect!", "Error connecting to     database: "+db.lastError().driverText());
   // qDebug()<<"Failed!!!!";
}

if(open)
{
QSqlQuery query;
query.exec("create table person "
      "(id integer primary key, "
      "firstname varchar(20), "
      "lastname varchar(30), "
      "age integer)");

}

 QSqlQuery query2;

query2.prepare("INSERT INTO person (id,firstname,lastname,age)VALUES(:ID,:FIRSTNAME,:LASTNAME,:AGE)"); query2.bindValue(":ID",1); query2.bindValue(":FIRSTNAME","ali"); query2.bindValue(":LASTNAME","alavi"); query2.bindValue(":AGE",24); query2.exec(); QSqlTableModel model; model.setTable("person"); model.select(); QSqlRecord record=model.record(0); result=record.value("firstname").toString(); }

QString CSqlConnect::getValue()
{
   return result;
}

CSqlConnect::~CSqlConnect()
{
db.close();
}

Upvotes: 0

Views: 273

Answers (1)

Frank Osterfeld
Frank Osterfeld

Reputation: 25155

You’re trying to create the SQLite file in the current working directory (./myfile.sqlite), which is most probably not writable from the app, on Android.

Better get a writable path from QStandardPaths explicitly:

const auto path = QStandardPaths::writableLocation(QStandardPaths::AppDataLocation);

errno = 0;
if (!QDir(path).mkpath()) {
    // return error, get details from strerror(errno)
    …
    return;
}

db.setDatabaseName(path + QStringLiteral("/myfile.sqlite"));
if (!db.open()) {
   // handle error
   …
   return;
}

…

Upvotes: 1

Related Questions