1

so my problem, I trying to create a sqlite database with QT. So...i use this code:

QString dbName = "apo.sqlite";
db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbName);

if( QFile::exists(dbName))
{
    db.setDatabaseName(dbName);
    db.database(dbName,true);
    qDebug()<<"DATABASE EXIST";

    if(db.open())
    {
        QSqlQuery query(db);
        query.prepare("INSERT INTO settings (username, password, remember_login) VALUES ('aaa', 'bbb', '1')");
        query.exec();

        qDebug() << "DATABASE OPEN";
        query.prepare("SELECT * FROM `settings`");
        query.exec();

        while (query.next())
        {
            qDebug() << "USERNAME" << query.value("username").toString();
        }
    }
    else
    {
        qDebug() << "DATABASE CLOSED";
    }
}
else {
    qDebug() << "DATABASE NOT EXIST, I CREATE ONE";

    if(!db.isOpen()) {
        qDebug() << "ERROR I CAN'T OPEN DATABASE";
    }
    else
    {
        QSqlQuery q;
        q.prepare("CREATE TABLE `settings` (`id` INTEGER PRIMARY KEY AUTOINCREMENT, `username` TEXT, `password` TEXT, `remember_login` TEXT);");
        q.exec();

        qDebug() << "DB opened";

        QSqlQuery query(db);
        query.prepare("INSERT INTO settings (username, password, remember_login) VALUES ('aaa', 'bbb', '1')");
        query.exec();

        query.prepare("SELECT * FROM settings");
        query.exec();

        while (query.next())
        {
            qDebug() << "USERNAME" << query.value("username").toString();
        }
    }
}

Well, you can see that i've set my code to check first open on the app, on the first open i create a db. On the second open, and over, i read the database. this code works on android device, but on iOS device this code don't work, why? Maybe the cross platform don't supports this code ?

I use qt 5.9 I don't understand where i wrong. Thanks for the help.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Mr. Developer
  • 3,295
  • 7
  • 43
  • 110

1 Answers1

1

the solutions to works on iOS is:

QString dbName = "myDB";

QString dbLocation = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation);

db = QSqlDatabase::addDatabase("QSQLITE");
db.setDatabaseName(dbLocation + "/" +dbName);
db.database(dbLocation + "/" +dbName);
db.databaseName();

to works on iOS you must use a path, add the path before database name. I tested some path, but work only when you use DocumentsLocation. You can see on this link from apple developer. Now work on cross platforms, Android and iOS too.

Mr. Developer
  • 3,295
  • 7
  • 43
  • 110