ionic2本地數據庫SQLite的增刪改查


 有什么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('查詢錯誤');
    });
  }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM