Import an External SQLite database to my project



  • Hi everybody,
    I'm interested in importing an external SQLite database to my project.
    When using the QT Quick Local Storage

    LocalStorage.openDatabaseSync("QQmlExampleDB", "1.0", "The Example QML SQL!", 1000000);
    

    The problem is that, the program generates a NEW database, and if it's possible I'm interested in open an existing database.

    Any idea?

    Thank you very much!



  • The ideas are two:

    1. copies all tables from one DB to another
    2. change name of DB file and replace one DB on another


  • HI @aliks-os ,
    thanks for your answer,
    and how I could to for example the first idea, copy all tables from one DB to another?

    My problem is that I don't know how to acces to the first database on QML.

    Thank you



  • I think you need change your code in QML/Qt to open at once two DB.
    What the problem to have access to the first DB?


  • Qt Champions 2016

    @carles.sole.grau said:

    Hi I dont have QML installed so cant test but I was wondering
    Docs at
    http://doc.qt.io/qt-5/qtquick-localstorage-qmlmodule.html
    says
    "They are stored in the Databases subdirectory of QQmlEngine::offlineStoragePath()"

    So maybe its possible to run your code so it creates a new database
    then output the path from offlineStoragePath()
    Then go there with Explorer
    Close your app.
    and copy over the new DB QQmlExampleDB with the
    full db you have also renamed to QQmlExampleDB
    or simply place the new db there and see if it then can open it?



  • Finally, I could solve my problem, all the things I have had to do are:

    In main.cpp I add this code:

    QDir dir("./Databases");
    if (!dir.exists()) {
        dir.mkpath(".");
    }
    QString new_name = QString(QCryptographicHash::hash(("nameofthecopiedDB"),QCryptographicHash::Md5).toHex());
    
    QFile file(":/SQLite/nameofsourceDB.sqlite");
    file.copy("./Databases/" + new_name + ".sqlite");
    file.close();
    

    Since I have the DB I would to use in my project in SQLite folder from my resources (:, indicates resources).
    The QCryptographicHash::hash function is necessary because in the:

    openDatabaseSync(string name, string version, string description, int estimated_size, jsobject callback(db))
    

    the name is passed with md5 codification: "the path to a database is QQmlEngine::offlineStoragePafh + md5(name) + ".sqlite". Where name is 1st parameter of openDatabaseSync"

    And then, in QML file, the openDatabaseSync() function:

    db = Sql.LocalStorage.openDatabaseSync('nameofthecopiedDB',"1.0","description",1000000,"QSQLITE")
    

    Thank you!


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.