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 {
    width: 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();
    }
}

  

 

 

posted on 2012-09-19 15:21 chuncn 阅读(...) 评论(...) 编辑 收藏

导航

公告