ionicsqlite的使用

iodinetech發表於2017-02-13

這方面的文章比較匱乏啊,博主這個菜鳥費了好大的力氣才學個差不多。

(PS:博主半路出家,尚是菜鳥,寫的東西自己跑起來並沒有什麼問題但不敢保證寫的一定對,語言也很隨意,僅供參考。另,期待各位前輩的指教)


新增外掛:

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git

注意:用這個外掛,需要在真機或模擬器上執行,ionic serve不支援呼叫真機api的外掛
新增完外掛,得在index.html裡面加一行

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
        <script src="lib/ionic/js/ionic.bundle.js"></script>
        <script src="js/ng-cordova.min.js"></script>                //就這行,加上
        <script src="cordova.js"></script>
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter">

然後在app.js裡面,宣告一個db,在.run同一行的括號里加上”$cordovaSQLite”

var db = null;         //app.js最上面初始化一個值為null的db變數
 
var example = angular.module(`starter`, [`ionic`, `ngCordova`])   //這個ngCordova忘了是不是要自己填進來了,沒有就填上
    .run(function($ionicPlatform, $cordovaSQLite) {               //"$cordovaSQLite"寫在這裡
        $ionicPlatform.ready(function() {
            if(window.cordova && window.cordova.plugins.Keyboard) {
                cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
            }
            if(window.StatusBar) {
                StatusBar.styleDefault();
            }
            db = $cordovaSQLite.openDB("my.db");                  //這個就是建立db了。好像不用提前建立,直接open就行。。
            $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
                                              //建立一個表,前面是資料庫名字,後面是sql語句了
        });
    });

ok,到此為止我們的資料表建立完成。

接下來是運算元據庫

運算元據庫,需要在對應controller中新增$cordovaSQLite

.controller(`AddThingsCtrl`, function($scope, $cordovaSQLite, $scope, $ionicActionSheet, $timeout) {//就第二個

然後就可以在controller裡面寫函式了

1.insert

  $scope.add = function(name, introduce, pic, price, detail){         //外面傳進來的引數
    var qInsert = "INSERT INTO cafe (name, introduce, pic, price, detail) VALUES ( ?, ?, ?, ?, ?)";    //SQL
    $cordovaSQLite.execute(db, qInsert, [name, introduce, pic, price, detail]).then(function(res) {    //三個引數,分別是資料庫名,執行的sql語句,和待填入sql語句中對應位置的引數。後面是執行完畢的回撥函式,res是返回的物件
          console.log("INSERTED");
        }, function (err) {
          console.log("Error");
        })
  }

上面的add函式的引數和sql語句中的問號、中括號中的引數不需要保持一致

這是我的一個函式,寫的很難看,但是能說明問題,見笑了……

HTML:

 <button class="button button-positive button-block" ng-click="add(name, introduce, pic)">完成新增</button>

controller.js:

$scope.idUnoccupied = ...;
$scope.lastSort = ...;
  $scope.add = function(name, introduce, pic){
    var qInsert = "INSERT INTO cafe (id, father, name, sort, introduce, pic) VALUES (?, ?, ?, ?, ?, ?)";
    $cordovaSQLite.execute(db, qInsert, [$scope.idUnoccupied, -1, name, $scope.lastSort, introduce, pic]).then(function(res) {
          console.log("INSERTED");
        }, function (err) {
          console.error(err);
        })
  }

2.select


//有引數的select
  $scope.selectByPrice = function(byPrice){
    var select = "SELECT * FROM cafe WHERE price = ?";
    $cordovaSQLite.execute(db, select, [byPrice]).then(function(res) {    //byPrice就是引數
            if(res.rows.length > 0) {
                console.log(res.rows.item(0));           //這個就是物件。item()是一個拿物件的函式,引數是角標
                console.log(res.rows.item);               //需要拿什麼值,直接item(0).xxx就行了
            } else {
                console.log("No results found");
            }
        }, function (err) {
            console.error(err);
        });
  }


//沒有引數的select
  $scope.idUnoccupied = 0;
  $scope.ifCanInsert = function(){                                //查詢種類id列空缺位置
    var queryFindUnoccupied = "SELECT MIN(id+1) FROM cafe AS a WHERE NOT EXISTS (SELECT id FROM cafe WHERE id=a.id+1)";
    $cordovaSQLite.execute(db, queryFindUnoccupied, []).then(function(res) {    //沒有引數,中括號裡不填東西就是了
            if(res.rows.item(0)["MIN(id+1)"] == null){$scope.idUnoccupied = 0;}
            else{$scope.idUnoccupied = res.rows.item(0)["MIN(id+1)"];}          //返回來的物件的名字是MIN(id+1),直接寫item(0).MIN(id+1)會被當成函式查不了,所以這麼寫。
            console.log($scope.idUnoccupied);
        }, function (err) {
            console.error(err);
        });
  }

另外兩個操作應該就不用寫了吧……

需要注意的是,資料庫的操作需要裝置準備好,即app.js中的.run執行完,才能使用。如果在.run執行前就直接執行資料庫操作,那麼被操作的資料庫就是null,會報錯。這時在終端/cmd中按個r,reset一下就可以正常用了(當然,前提是沒有寫錯的地方。。)

刪資料庫,就是在app.js中寫


$cordovaSQLite.deleteDB("my.db");