有什么ionic2方面的問題可以在這條博客下留言,我會盡量給大家解答
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('查詢錯誤'); }); }