[Android]Cordova使用Sqlite資料庫

什麼是SQLite?

SQLite是一個軟體資料庫,不需要架設在伺服端的自主資料庫,用來存放數據資料。

行動裝置上對於資料的存取需求相對比少,不太需要大量的記憶體及cpu,對於行動裝置是個很好的選擇。

當我們利用Cordova/PhoneGap開發行動裝置時,可以增加plugin來支援Sqlite的使用,再結合html 5、CSS、Javascript就可以存取資料並顯示其結果。

Cordova plugin SQLite

https://github.com/brodysoft/Cordova-SQLitePlugin

A Cordova/PhoneGap plugin to open and use sqlite databases on Android/iOS/WP(8) with HTML5 Web SQL API

Native interface to sqlite in a Cordova/PhoneGap plugin for Android/iOS/WP(8), with HTML5 Web SQL API

License for Android & WP(8) versions: MIT or Apache 2.0

License for iOS version: MIT only

舊的專案網址

首先把Sqlite plugin 增加進入專案

cd 專案目錄
cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin

可以看到專案裡出現了需要的source

CordovaPluginSqlite

如何在Javascript中存取Sqlite呢?

1.首先需要在Device Ready後才可以open DataBase

document.addEventListener("deviceready", onDeviceReady, false);

// Cordova is ready
function onDeviceReady() {
  var db = window.sqlitePlugin.openDatabase({name: "my.db"});
  // ...
}

2.execute SQL

create table , drop table ,insert table,select table

db.transaction(function(tx) {
    tx.executeSql('DROP TABLE IF EXISTS test_table');
    tx.executeSql('CREATE TABLE IF NOT EXISTS test_table (id integer primary key, data text, data_num integer)');

    // demonstrate PRAGMA:
    db.executeSql("pragma table_info (test_table);", [], function(res) {
      console.log("PRAGMA res: " + JSON.stringify(res));
    });

    tx.executeSql("INSERT INTO test_table (data, data_num) VALUES (?,?)", ["test", 100], function(tx, res) {
      console.log("insertId: " + res.insertId + " -- probably 1");
      console.log("rowsAffected: " + res.rowsAffected + " -- should be 1");

      db.transaction(function(tx) {
        tx.executeSql("select count(id) as cnt from test_table;", [], function(tx, res) {
          console.log("res.rows.length: " + res.rows.length + " -- should be 1");
          console.log("res.rows.item(0).cnt: " + res.rows.item(0).cnt + " -- should be 1");
        });
      });

    }, function(e) {
      console.log("ERROR: " + e.message);
    });

 

發表迴響