Use SQLite Instead of Local Storage In Ionic Framework【转】

Switching to object-based data storage can often be tough.  If you’re trying to start Phonegap or Ionic Framework development and are coming from native development, the whole local storage concept can be a tough one to grasp.  Or maybe you just prefer a structured query language (SQL) when working with your data.

Not to worry, because there is a plugin for that!

Making use of the Cordova SQLite plugin by Chris Brody, you can use a SQLite data source for managing your data in Android and iOS.  Pair this withngCordova and you can better compliment your Ionic Framework development with an AngularJS experience.

Like with all my tutorials, let’s start by creating a fresh Ionic project:

ionic start IonicProject blank
cd IonicProject
ionic platform add android
ionic platform add ios

Remember, if you’re not on a Mac computer, you cannot add and build for the iOS platform.

The next thing we want to do is add the SQLite plugin.  This can be done by running the following command:

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

  

Because this is an Ionic Framework article, we’re going to make use of ngCordova as it tends to make life pretty easy after including it.

Download the latest release and copy ng-cordova.min.js into your www/js directory.

With the library file included, we now need to include it in our project.  Open your index.html file and add the following highlighted line:

<!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">

  

It is very important you add it above the cordova.js line otherwise it will not work.

One more thing must be added before we can start using ngCordova.  We need to inject it into our angular.module, found in app.js, like the following:

angular.module(‘starter‘, [‘ionic‘, ‘ngCordova‘])

  

It’s time to start using this library.  For simplicity, we are going to do the following:

  1. Create a new table called people
  2. Insert two people into this new table
  3. Select all the people found in our table with my last name

Before we start coding, it is very important to note that database activity can only be done when the onDeviceReady() method has fired.  With this in mind, I’m going to open the database in the modules .run() method like so:

var db = null;

var example = angular.module(‘starter‘, [‘ionic‘, ‘ngCordova‘])
    .run(function($ionicPlatform, $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");
            $cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS people (id integer primary key, firstname text, lastname text)");
        });
    });

  

Take a look at the lines that I highlighted.  We want to have access to the database globally so I created a variable outside of any method or controller.  To use the ngCordova functions we need to include $cordovaSQLite in the .run() method.  Finally, you can see that I’ve created a new database called my.db and a fresh table called people.

This leaves us with a usable database ready for activity in our controllers.  Take the following for example:

 1 example.controller("ExampleController", function($scope, $cordovaSQLite) {
 2
 3     $scope.insert = function(firstname, lastname) {
 4         var query = "INSERT INTO people (firstname, lastname) VALUES (?,?)";
 5         $cordovaSQLite.execute(db, query, [firstname, lastname]).then(function(res) {
 6             console.log("INSERT ID -> " + res.insertId);
 7         }, function (err) {
 8             console.error(err);
 9         });
10     }
11
12     $scope.select = function(lastname) {
13         var query = "SELECT firstname, lastname FROM people WHERE lastname = ?";
14         $cordovaSQLite.execute(db, query, [lastname]).then(function(res) {
15             if(res.rows.length > 0) {
16                 console.log("SELECTED -> " + res.rows.item(0).firstname + " " + res.rows.item(0).lastname);
17             } else {
18                 console.log("No results found");
19             }
20         }, function (err) {
21             console.error(err);
22         });
23     }
24
25 });

I’ve gone ahead and created two very basic functions.  The insert function will add a first and last name record into the database while the select function will find records by last name.  Basic, but I hope you get the idea.

Something to note about my controller though.  I am not doing these database calls from inside an onDeviceReady() function.  Had these functions been fired when the controller loads, they probably would have failed.  Since I am basing the database activity off button clicks, it is probably safe to assume the device and database is ready for use.

If you wish to delete any of your SQLite databases you can do so by including the following:

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

注:原文地址:https://blog.nraboy.com/2014/11/use-sqlite-instead-local-storage-ionic-framework/#

时间: 2024-10-23 06:09:06

Use SQLite Instead of Local Storage In Ionic Framework【转】的相关文章

Ionic2学习笔记(8):Local Storage& SQLite

作者:Grey 原文地址: http://www.cnblogs.com/greyzeng/p/5557947.html ? ? ? ? ?Ionic2可以有两种方式来存储数据,Local Storage和SQLite ? LocalStorage ? 因为比较容易访问,所以不适合存比较敏感性的数据 比如可以存储: 用户是否登录的信息. 一些session信息等 具体用法: 进入项目目录:cd MyFirstApp 在主页设置一个按钮,点击按钮,获取LocalStorage的数据并打印在控制台

HTML5使用local storage存储的数据是如何保存在本地的

HTML5使用local storage存储的数据是如何保存在本地的?(我使用的是chrome浏览器,chrom浏览器是用sqlite来保存本地数据的) HTML5 的local storage 是通过浏览器在本地存储的数据. 基本使用方法如下: <script type="text/javascript"> localStorage.firstName = "Tom"; alert(localStorage.firstName); </scrip

HTML5的local storage存储的数据到底存到哪去了

原文地址:http://zhidao.baidu.com/link?url=m6p5MLv0R46lDCd_Vnrry4XOMbdCwgV5fzs3tj5Jeyht1nPkAZ9OrO23njYBY15UMobx63X1MdP-EwKKqerm-_zSugwqqLin_TsClwOrH_O 基本使用方法如下:localStorage.name = "k1w1"; 这样的话,你的本地磁盘中就会有个数据库存下了这个数据.我无法接受数据写到了我的本地磁盘而我找不到它的确切位置,于是通过寻找发

HTML5移动开发之路(19)——HTML5 Local Storage(本地存储)

本文为 兄弟连IT教育 机构官方 HTML5培训 教程,主要介绍:HTML5移动开发之路(19)--HTML5 Local Storage(本地存储) 一.浏览器存储的发展历程 本地存储解决方案很多,比如Flash SharedObject.Google Gears.Cookie.DOM Storage.User Data.window.name.Silverlight.Open Database等. 借用网上的一张图来看下目前主流的本地存储方案: Cookie: 在web中得到广泛应用,但局限

【JEECG技术博文】Local storage &amp;amp; easyui extensions

1. Local storage背景 cookie弊端:同域内http请求都会带cookie,添加带宽和流量:有个数和限制大小(约4K). 在HTML5中,本地存储是一个window的属性.包含localStorage和sessionStorage.从名字应该能够非常清楚的辨认二者的差别.前者是一直存在本地的,后者仅仅是伴随着session,窗体一旦关闭就没了. 二者用法全然同样. 2. Jquery.storage.js插件 项目主页,api请參考http://ek.alphaschildre

【JEECG技术博文】Local storage &amp; easyui extensions

1. Local storage背景 cookie弊端:同域内http请求都会带cookie,增加带宽和流量:有个数和大小限制(约4K). 在HTML5中,本地存储是一个window的属性,包括localStorage和sessionStorage,从名字应该可以很清楚的辨认二者的区别,前者是一直存在本地的,后者只是伴随着session,窗口一旦关闭就没了.二者用法完全相同. 2. Jquery.storage.js插件 项目主页,api请参考http://ek.alphaschildren.o

[并发并行]_[C/C++]_[使用线程本地存储Thread Local Storage(TLS)调用复制文件接口的案例]

使用场景: 1. 在复制文件时,一般都是一个线程调用一个接口复制文件,这时候需要缓存数据,如果每个文件都需要创建独立的缓存,那么内存碎片是很大的. 如果创建一个static的内存区,当多线程调用同一个接口时,多个线程同时使用同一个static缓存会造成数据污染.最好的办法是这个缓存只对这个线程可见, 当线程创建时创建缓存区,当线程结束时销毁缓存区. 2. 代码里有注释: test.cpp #include <iostream> #include "pthread.h" #i

cookie ,session Storage, local storage

先来定义: cookie:是网站为了标识用户身份存储在本地终端的数据,其数据始终在APP请求中存在,会在服务器和浏览器中来回传递 数据大小不超过4k, 可以设置有效期,过了有效期自动删除 session Storage和local Storage 不会自动把数据发给服务器,仅在本地保存, 数据大小可达到5M 存储时间久,不会自己消失,必须自动删除 local Storage:会随窗口关闭而删除 代码: 1 $(function () { 2 $(document).click(function

HTML5之Local Storage

HTML5 STORAGE SUPPORT IE FIREFOX SAFARI CHROME OPERA IPHONE ANDROID 8.0+ 3.5+ 4.0+ 4.0+ 10.5+ 2.0+ 2.0+ Local Storage Detection: ## 方法一function supports_local_storage() { try { return 'localStorage' in window && window['localStorage'] !== null; }