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