Recently I needed to create database from QML application on which I am working. I wanted to separate database related code from QML and created javascript file to handle database related work. I had to struggle a little to make storage API work from javascript, below are my findings.
As you might already know to use sqllite database in QML you will need to import LocalStorage API.
As you might already know to use sqllite database in QML you will need to import LocalStorage API.
import QtQuick.LocalStorage 2.0 as SqlThis will work for QML but if you want to use it from javascript then you will need to use following syntax.
.import QtQuick.LocalStorage 2.0 as SqlNow you should be able to use LocalStorage API in javascript. LocalStorage related API can be accessed by using LocalStorage object and we imported LocalStorage module as Sql, we will need to use access LocalStorage object from Sql scope. Like below.
var db = Sql.LocalStorage.openDatabaseSync("TestDB", "1.0", "Description", 100000);Now you can use this db object to create table and select values from it just like you do in QML. Following is sample example.
function getDatabase() { var db = Sql.LocalStorage.openDatabaseSync("TestDB", "1.0", "Description", 100000); //create table db.transaction( function(tx) { var query="CREATE TABLE IF NOT EXISTS TEST(Id INTEGER PRIMARY KEY, Title TEXT)"; tx.executeSql(query); }); return db; } function printValues() { var db = getDatabase(); db.transaction( function(tx) { var rs = tx.executeSql("SELECT * FROM TEST"); for(var i = 0; i < rs.rows.length; i++) { var dbItem = rs.rows.item(i); console.log("ID:"+ dbItem.Id + ", TITLE:"+dbItem.Title); } }); }
Thanks! I was trying to call Sql.openDatabaseSync and felt totally puzzled of why it did not work, but then I found your article.
ReplyDeleteThis is very confusing way of accessing LocalStorage, but guess I will be better off now
I faced similar issue, so I thought to share it. I am glad that it helped.
Deletethanks for sharing
ReplyDeleteThanks for sharing.....
ReplyDeleteCould you get an sql file and query the sql as well?
ReplyDelete