ionic2本地資料庫SQLite的增刪改查
阿新 • • 發佈:2019-02-15
1.在終端執行這兩個命令
$ ionic cordova plugin add cordova-sqlite-storage
$ npm install --save @ionic-native/sqlite
2.在app.module.ts中新增
import { SQLite } from '@ionic-native/sqlite';
3.在app.module.ts的providers:[]中加入SQLite
4.在需要用到SQLite的ts檔案中加入
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
5.在需要用到SQLite的ts檔案的constructor中加入
constructor(private sqlite: SQLite,) {}
6.資料庫操作
//資料庫SQLite操作 database: SQLiteObject; ngOnInit() { this.initDB(); } initDB(){ this.sqlite.create({ name: 'data.db', location: 'default' }) .then((db: SQLiteObject) => { db.executeSql('create table if not exists saveQuestion(id INTEGER PRIMARY KEY AUTOINCREMENT, questionName text NOT NULL)', {})//建表 .then(() => console.log('Executed SQL')) .catch(e => console.log(e)); this.database = db; }); } //插入資料 insert(params){ //console.log(params); //獲取當前時間 var date: string = new Date().toLocaleDateString(); var time: string = new Date().toTimeString().substring(0,5);var datetime: string = date + " " + time; console.log(datetime); this.database.executeSql("INSERT INTO saveQuestion (questionName,important) VALUES (?,?);",[params.questionName,params.important]) .then(() => alert('暫存成功')) .catch(e => console.log(e));//插入資料 }
//修改資料 update(params){ //console.log(params); var date: string = new Date().toLocaleDateString(); var time: string = new Date().toTimeString().substring(0,5); var datetime: string = date + " " + time; console.log(datetime); this.database.executeSql("UPDATE saveQuestion set questionName=?,important=? WHERE id=?;",[params.questionName,params.important
])
.then(() => alert('修改成功')) .catch(e => console.log(e)); }
//刪除 buttonDelete(){ this.database.executeSql("DELETE FROM saveQuestion WHERE id=?;",[this.id]) .then(() => alert('刪除成功')) .catch(e => console.log(e));//刪除資料 }
//查詢 query() { this.database.executeSql("select * from saveQuestion",{}).then((data)=>{ },(error)=>{ console.log('查詢錯誤'); }); }https://www.cnblogs.com/huihuihui/p/6930412.html