· 8 years ago · Jan 26, 2018, 09:06 PM
1import { HttpClient } from '@angular/common/http';
2import { Injectable } from '@angular/core';
3import { SQLite, SQLiteObject } from '@ionic-native/sqlite';
4/*
5 Generated class for the DatabaseProvider provider.
6
7 See https://angular.io/guide/dependency-injection for more info on providers
8 and Angular DI.
9*/
10@Injectable()
11export class DatabaseProvider {
12
13 constructor(private sqlite: SQLite) {
14 }
15
16 public getDB(){
17 return this.sqlite.create({
18 name:'historico.db',
19 location: 'default'
20 });
21 }
22
23 public createDatabase(){
24 return this.getDB()
25 .then((db: SQLiteObject) =>{
26 this.createTables(db);
27
28 this.insertDefaultItems(db);
29
30 })
31 .catch(e => console.error(e));
32 }
33
34
35 private createTables(db: SQLiteObject){
36 db.sqlBatch([
37 ['CREATE TABLE IF NOT EXISTS historico(id integer primary key AUTOINCREMENT NOT NULL, cep INTEGER, logradouro TEXT, bairro TEXT, cidade TEXT, estado TEXT)'],
38
39 ])
40 .then(() => console.log('Tabela criada'))
41 .catch(e => console.error('Erro ao criar a tabela', e));
42 }
43
44 private insertDefaultItems(db: SQLiteObject){
45 db.executeSql('select COUNT(id) as qtd from historico',{})
46 .then((data: any) => {
47 //se não existe nenhum registro
48 if (data.rows.item(0).qtd == 0) {
49
50 //criando registros padrões
51
52 db.sqlBatch([
53 ['insert into historico (cidade) values (?)', ['PaulÃnia']],
54 ['insert into historico (cidade) values (?)', ['Campinas']],
55 ['insert into historico (cidade) values (?)', ['Sumaré']],
56 ])
57 .then(() => console.log('Dados padrões incluÃdos'))
58 .catch(e => console.error('Erro ao incluir dados padrões', e));
59 }
60 })
61 }
62
63}