executeSql将结果抛出错误

时间:2018-10-05 06:28:51

标签: sqlite ionic-framework

我不明白为什么以下代码会这样工作:所有结果都进入catch块。在“ select * from danceMoves”之后的最后一个catch块实际上会将“ swag”写入控制台。

这是一个使用ionic start创建的简单项目,然后添加cordova-sqlite-storage。遵循Ionic网站文档。

public testSQLite() {
this.sqlite.create({
  name: 'data.db',
  location: 'default'
})
  .then((db: SQLiteObject) => {
    db.executeSql('create table if not exists danceMoves(name VARCHAR(32))')
      .then(() => { debugger; console.error('Executed SQL') })
      .catch(e => { debugger; console.error(e) })
      .then(() => { debugger; return db.executeSql("insert into danceMoves(name) values('swag')") })
      .then(() => { debugger; return db.executeSql("select * from danceMoves") })
      .then(result => { debugger; console.log(result.rows.item(0).name) })
      .catch(error => { debugger; console.error(error) })
      .then(() => { debugger; return db.executeSql("select * from danceMoves") })
      .then(result => { debugger; console.log(result.rows.item(0).name) })
      .catch(result => { debugger; console.log(result.rows.item(0).name)});
  })
  .catch(e => { debugger; console.error(e) });
}

1 个答案:

答案 0 :(得分:1)

好的,我找到了可能的解决方案(至少它为我解决了问题)。 executeSql方法需要两个参数:一个语句和一个params数组。

该语句可能包含参数(例如SELECT * FROM table WHERE id=?),这些参数可以使用params数组(例如[1])中给出的对象来解析。

params数组参数被标记为可选,因为没有参数可能会起作用。但是,如果未给出数组,则查询的结果集将作为错误而不是返回返回。为了解决这个问题,我总是指定一个空数组作为第二个参数,这为我解决了这个问题。

示例调用: db.executeSql(SELECT * FROM danceMoves, []).then(result => console.log(result.rows.item(0).name)