Ionic2調用本地SQlite執行個體,ionic2sqlite執行個體

來源:互聯網
上載者:User

Ionic2調用本地SQlite執行個體,ionic2sqlite執行個體

普通的app用ionic內建的Storage儲存索引值對的方式可以滿足日常的使用,但是有時候遇到一些奇怪的需求。比如說有個網友留言說做一個離線版的App,怎樣調用本地Sqlite執行SQL語句。問題描述清楚直接上代碼。

需要說明的是SQLite是手機內建的資料庫儲存方式,在Ionic2中需要安裝相應的外掛程式和安裝包。過程很簡單

第一步

安裝外掛程式、並加入項目

$ ionic plugin add cordova-sqlite-storage$ npm install --save @ionic-native/sqlite

第二步

把服務加入到src/app/app.moudle.ts

...import { SQLite } from '@ionic-native/sqlite';...providers: [ ... SQLite]...

第三步

使用資料庫,常規來說,這一步應該封裝成公用服務或者工具類。類中是具體的建立資料庫,調用資料庫,CRUD等方法。這裡只是說明原理,直接調用

import { Component } from '@angular/core';import { SQLite, SQLiteObject } from '@ionic-native/sqlite';@Component({ selector: 'page-hello-ionic', templateUrl: 'hello-ionic.html'})export class HelloIonicPage { constructor(       private sqlite: SQLite) { } database :SQLiteObject; ngOnInit(){  this.initDB(); } initDB(){  this.sqlite.create({   name: 'data.db',   location: 'default'  })  .then((db: SQLiteObject) => {  db.executeSql('create table t_log(name VARCHAR(32))', {})//建表   .then(() => console.log('Executed SQL'))   .catch(e => console.log(e));  this.database = db;  db.executeSql("insert into t_log values('123')",{});//插入資料  })  .catch(e => console.log(e)); }//查詢query() {  let results = this.database.executeSql("select * from t_log",{});  alert(data.rows.length);  alert(data.rows.item(0).name);  }) }}

最後一步

這一步一定要產生app安裝到手機才能得到結果,畢竟是調用手機內建的SQLite。
ionic build android

用上面的命令構建APP並安裝到手機看看效果吧

以上就是本文的全部內容,希望對大家的學習有所協助,也希望大家多多支援幫客之家。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.