QML uses Sqlite database

In the program, we often need to persist some data, such as some setting information and program configuration. QML does not directly access local files, but it can be accessed through

The Offline Storage API accesses the local Sqlite database to achieve its purpose.

 

First create a storage.js in the qml directory

[javascript]  view plain copy  
  1. //storage.js  
  2. // First create a helper method to connect to the database  
  3. .import QtQuick.LocalStorage 2.0 as Sql

  4. function getDatabase() {  
  5.      return Sql.LocalStorage.openDatabaseSync("MyAppName""1.0""StorageDatabase", 100000);  
  6. }  
  7.    
  8. // When the program is opened, initialize the table  
  9. function initialize() {  
  10.     var db = getDatabase();  
  11.     db.transaction(  
  12.         function(tx) {  
  13.             // If the setting table does not exist, create one  
  14.             // If the table exists, skip this step  
  15.             tx.executeSql('CREATE TABLE IF NOT EXISTS settings(setting TEXT UNIQUE, value TEXT)');  
  16.       });  
  17. }  
  18.    
  19. // insert data  
  20. function setSetting(setting, value) {  
  21.    var db = getDatabase();  
  22.    var res = "";  
  23.    db.transaction(function(tx) {  
  24.         var rs = tx.executeSql('INSERT OR REPLACE INTO settings VALUES (?,?);', [setting,value]);  
  25.               //console.log(rs.rowsAffected)  
  26.               if (rs.rowsAffected > 0) {  
  27.                 res = "OK";  
  28.               } else {  
  29.                 res = "Error";  
  30.               }  
  31.         }  
  32.   );  
  33.   return res;  
  34. }  
  35.   
  36.  // 获取数据  
  37. function getSetting(setting) {  
  38.    var db = getDatabase();  
  39.    var res="";  
  40.    db.transaction(function(tx) {  
  41.      var rs = tx.executeSql('SELECT value FROM settings WHERE setting=?;', [setting]);  
  42.      if (rs.rows.length > 0) {  
  43.           res = rs.rows.item(0).value;  
  44.      } else {  
  45.          res = "Unknown";  
  46.      }  
  47.   })  
  48.   return res  
  49. }  

 然后就可以在qml里调用了

[php]  view plain  copy
  1. import Qt 4.7  
  2. //引入storage.js,起个别名Storage,以供后面使用  
  3. import "storage.js"as Storage   
  4. Rectangle {  
  5.     width: 360  
  6.     height: 360  
  7.     id: screen  
  8.     Text {  
  9.         id: textDisplay  
  10.         anchors.centerIn: parent  
  11.     }  
  12.     Component.onCompleted: {  
  13.         // initialize the database  
  14.         Storage.initialize();  
  15.         // assign  
  16.         Storage.setSetting("mySetting","myValue");  
  17.         //Get a value and write it in textDisplay  
  18.         textDisplay.text = "The value of mySetting is:\n" + Storage.getSetting("mySetting");  
  19.     }  
  20. }  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325518181&siteId=291194637