ionic2本地数据库SQLite的增删改查

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值