我的应用程序应该在哪里创建一个SQLite数据库实例?

时间:2017-05-20 12:03:32

标签: sqlite ionic-framework ionic2

我正在创建一个将使用SQLite数据库存储数据的Ionic 2移动应用程序。我知道我必须使用下面的代码来访问数据库:

this.sqlite.create({
    name: 'data.db',
    location: 'default'
})
.then((db: SQLiteObject) => {
    db.executeSql('create table danceMoves(name VARCHAR(32))', {})
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    })
.catch(e => console.log(e));

考虑到我的应用程序访问数据库时有几个页面,我的问题是我应该何时使用create方法获取db对象实例:每次我需要执行命令还是我应该执行一次并将db实例放在全局变量中?

1 个答案:

答案 0 :(得分:1)

您可以创建一个单独的提供程序,作为sqlite数据库的接口。

@Injectable()
export class StorageService {

 constructor(private sqlite: SQLite){
  this.sqlite.create({
    name: 'data.db',
    location: 'default'
})
.then((db: SQLiteObject) => {
    db.executeSql('create table danceMoves(name VARCHAR(32))', {})
        .then(() => console.log('Executed SQL'))
        .catch(e => console.log(e));
    })
.catch(e => console.log(e));
}


//other db access functions like insert, get, delete etc.
}

app.module.ts 中,将其设置为提供者并在任何需要的地方注入。

相关问题