代码干货 | ionic sqlite的使用

本文来源于阿里云-云栖社区,原文点击这里


这方面的文章比较匮乏啊,博主这个菜鸟费了好大的力气才学个差不多。

(PS:博主半路出家,尚是菜鸟,写的东西自己跑起来并没有什么问题但不敢保证写的一定对,语言也很随意,仅供参考。另,期待各位前辈的指教)


添加插件:

cordova plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git
注意:用这个插件,需要在真机或模拟器上运行,ionic serve不支持调用真机api的插件
添加完插件,得在index.html里面加一行


    
        
        
        
        
        
        
                        //就这行,加上
        
        
    
    

然后在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:

 

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);
        })
  }


>>>展开全文

你可能感兴趣的:(代码干货)