zoukankan      html  css  js  c++  java
  • sqlite in qt

    storage.js

    //storage.js
    
    //数据库文件默认路径:QDeclarativeEngine::offlineStoragePath()
    //数据库文件路径更改:QDeclarativeEngine::setOfflineStoragePath(const QString & dir)
    
    // 打开并获取数据库对象
    function getDatabase() {
         return openDatabaseSync("MyApp", "1.0", "StorageDatabase", 100000);
    }
     
    //初始化表
    function initialize() {
        var db = getDatabase();
        db.transaction(
            function(tx) {
                tx.executeSql('CREATE TABLE IF NOT EXISTS myTable(name TEXT UNIQUE, study TEXT)');
    	  });
    }
     
    //写入数据库
    function setSetting(name, study) {
       var db = getDatabase();
       var res = "";
       db.transaction(function(tx) {
            var rs = tx.executeSql('INSERT OR REPLACE INTO myTable VALUES (?,?);', [name,study]);
                  if (rs.rowsAffected > 0) {
                    res = "OK";
                  } else {
                    res = "Error";
                  }
            }
      );
      return res;
    }
    
    //获取数据1
    function getSetting(name) {
       var res="";
       var db = getDatabase();
       db.transaction(function(tx) {
         var rs = tx.executeSql('SELECT name,study FROM myTable WHERE name=?;', [name]);
         if (rs.rows.length > 0) {
              res = rs.rows.item(0).name;
         } else {
             res = "Unknown";
         }
      })
      return res
    }
    
    //获取数据2
    function getSetting2() {
      var r = "";
      var db = getDatabase();
      db.transaction(function(tx) {
        var rs = tx.executeSql('SELECT name,study FROM myTable');
        for(var i = 0; i < rs.rows.length; i++) {
            r += rs.rows.item(i).name + ", " + rs.rows.item(i).study + "\r\n"
        }
        print(r);
     })
     return r
    }
    

    main.qml

    import QtQuick 1.1
    import "storage.js" as Storage
    
    Rectangle {
         360
        height: 360
        id: screen
        Text {
            id: textDisplay
            anchors.centerIn: parent
        }
        Component.onCompleted: {
            // 初始化数据库
            Storage.initialize();
            // 赋值
            Storage.setSetting("张三","新疆大学");
            Storage.setSetting("李四","内蒙大学");
            //获取一个值,并把它写在textDisplay里
            //textDisplay.text = "The value of mySetting is:\n" + Storage.getSetting("mySetting");
            textDisplay.text = Storage.getSetting2();
        }
    }
    

      

  • 相关阅读:
    REST API注意事项
    Javascript addEventListener dispatchEvent
    Javascript常见操作
    MySql运算符
    Mysql数据类型
    MySql基本命令
    php学习
    javascript学习
    如何快速掌握一种技术
    站在K2角度审视流程--任务的独占与释放
  • 原文地址:https://www.cnblogs.com/chuncn/p/2693752.html
Copyright © 2011-2022 走看看