1. เปิดโฟลเดอร์ แล้วพิมพ์ cmd บน address bar พิมพ์ ionic start week10_sqlite blank
  2. พิมพ์ cd week10_sqlite
  3. เปิด visual studio code ไปที่ file open folder week10_sqlite
  4. กลับมาที่ cmd พิมพ์
    ionic cordova plugin add cordovasqlitestorage 
  5. พิมพ์ npm install @ionicnative/sqlite
  6. กลับไปที่ visual studio code ในโฟลเดอร์โปรเจ็คเราให้หา app.module.ts  ให้วาง import { SQLite } from ‘@ionic-native/sqlite/ngx’; และเพิ่ม SQLite ตรง provider ในไฟล์ app.module.ts ใส่โค้ดตามด้านล่าง

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { RouteReuseStrategy } from '@angular/router';
    
    import { IonicModule, IonicRouteStrategy } from '@ionic/angular';
    import { SplashScreen } from '@ionic-native/splash-screen/ngx';
    import { StatusBar } from '@ionic-native/status-bar/ngx';
    
    import { AppComponent } from './app.component';
    import { AppRoutingModule } from './app-routing.module';
    
    import { SQLite } from '@ionic-native/sqlite/ngx';
    
    @NgModule({
      declarations: [AppComponent],
      entryComponents: [],
      imports: [BrowserModule, IonicModule.forRoot(), AppRoutingModule],
      providers: [
        StatusBar,
        SplashScreen,
        SQLite ,
        { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
      ],
      bootstrap: [AppComponent]
    })
    export class AppModule {}
    

     

     

     

  7. หน้า home.page.ts ใส่โค้ดตามด้านล่าง
    //home.page.ts
    import { Component } from '@angular/core';
    
    import { SQLite, SQLiteObject } from '@ionic-native/sqlite/ngx';
    import { Platform } from '@ionic/angular';
    
    @Component({
      selector: 'app-home',
      templateUrl: 'home.page.html',
      styleUrls: ['home.page.scss'],
    })
    export class HomePage {
    
      databaseObj: SQLiteObject;
      name_model: string = "";
      row_data: any = [];
      readonly database_name: string = "freaky_datatable.db";
      readonly table_name: string = "myfreakytable";
    
      constructor(
        private platform: Platform,
        private sqlite: SQLite
      ) {
        this.platform.ready().then(() => {
          this.createDB();
        }).catch(error => {
          console.log(error);
        })
      }
    
    
      createDB() {
        this.sqlite.create({
          name: this.database_name,
          location: 'default'
        })
          .then((db: SQLiteObject) => {
            this.databaseObj = db;
            alert('freaky_datatable Database Created!');
          })
          .catch(e => {
            alert("error " + JSON.stringify(e))
          });
      }
    
      createTable() {
        this.databaseObj.executeSql('CREATE TABLE IF NOT EXISTS ' + this.table_name + ' (pid INTEGER PRIMARY KEY, Name varchar(255))', [])
          .then(() => {
            alert('Table Created!');
          })
          .catch(e => {
            alert("error " + JSON.stringify(e))
          });
      }
    
      insertRow() {
        if (!this.name_model.length) {
          alert("Enter Name");
          return;
        }
        this.databaseObj.executeSql('INSERT INTO ' + this.table_name + ' (Name) VALUES ("' + this.name_model + '")', [])
          .then(() => {
            alert('Row Inserted!');
            this.getRows();
          })
          .catch(e => {
            alert("error " + JSON.stringify(e))
          });
      }
    
      getRows() {
        this.databaseObj.executeSql("SELECT * FROM " + this.table_name, [])
          .then((res) => {
            this.row_data = [];
            if (res.rows.length > 0) {
              for (var i = 0; i < res.rows.length; i++) {
                this.row_data.push(res.rows.item(i));
              }
            }
          })
          .catch(e => {
            alert("error " + JSON.stringify(e))
          });
      }
    
      deleteRow(item) {
        this.databaseObj.executeSql("DELETE FROM " + this.table_name + " WHERE pid = " + item.pid, [])
          .then((res) => {
            alert("Row Deleted!");
            this.getRows();
          })
          .catch(e => {
            alert("error " + JSON.stringify(e))
          });
      }
    
    
    }
    

     

  8. home.page.html
    <ion-header>
      <ion-toolbar>
        <ion-title>
          Ionic 4 SQLite
        </ion-title>
      </ion-toolbar>
    </ion-header>
    
    <ion-content padding text-center>
    
      <ion-button expand="block" (click)="createDB()">
        Create DataBase
      </ion-button>
    
      <ion-button expand="block" (click)="createTable()">
        Create Table
      </ion-button>
    
      <ion-button expand="block" (click)="getRows()">
        Get Rows
      </ion-button>
    
    
      <ion-item-divider>
        <ion-input placeholder="Enter Name" [(ngModel)]="name_model"></ion-input>
        <ion-button expand="block" (click)="insertRow()">
          Insert Row
        </ion-button>
      </ion-item-divider>
    
    
    
      <ion-grid>
        <ion-row>
          <ion-col>
            Row ID
          </ion-col>
          <ion-col>
            Name
          </ion-col>
          <ion-col>
            Delete
          </ion-col>
        </ion-row>
        <ion-row *ngFor="let item of row_data">
          <ion-col>
            {{item.pid}}
          </ion-col>
          <ion-col>
            {{item.Name}}
          </ion-col>
          <ion-col>
            <ion-button (click)="deleteRow(item)" size="small" color="danger">
              <ion-icon name="trash"></ion-icon>
            </ion-button>
          </ion-col>
        </ion-row>
      </ion-grid>
    
    </ion-content>
    
  9. ไปที่ไฟล์ config.xml แก้ name และ widget id เป็น week10_sqlite ดังภาพ
  10. หลังจากนั้นเซฟทุกไฟลแล้วให้เปิด emulator android ขึ้นมา
  11. กลับมาที่ cmd พิมพ์ ionic cordova run android –emulator

By admin

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.