【问题标题】:executeSql with WHERE clause not returning any results in Phonegap带有 WHERE 子句的 executeSql 在 Phonegap 中不返回任何结果
【发布时间】:2013-10-10 23:22:57
【问题描述】:

我正在使用 Phonegap 开发一个应用程序。我创建了一个名为 location 的表,如下所示:

...
tx.executeSql('CREATE TABLE IF NOT EXISTS LOCATIONS (id unique, name, key, secret)');
...

我插入了一行:

...
tx.executeSql('INSERT INTO LOCATIONS (id, name, key, secret) VALUES (?, ?, ?, ?)', [1, "Some Name", "Some Key", "Some Secret"], success, error);
...

当我这样做时:

...
tx.executeSql('SELECT * FROM LOCATIONS', [ ], function(tx, results) {
  ...
}

我得到 results.rows.length 等于 1 并且 results.rows.item(0) 是:

[ {"id":1,"name":"Some Name","key":"Some Key","secret":"Some Secret"} ]

但是如果我这样做:

...
function findById(id) {
  tx.executeSql('SELECT * FROM LOCATIONS WHERE id = ?', [ id ], function(tx, results) {
    ...
  }
}
...
findById(1);

我得到的 results.rows.length 等于 0,而我希望它是 1。

有没有人遇到过类似的问题?

非常感谢!

【问题讨论】:

    标签: javascript sql cordova


    【解决方案1】:

    我知道问题所在。似乎在插入行时,字段“id”被创建为整数(因为传递的值是整数)。但是,当我访问 findById 时,我没有发送 1,而是发送了“1”。 “WHERE”子句需要一个整数,而它正在寻找一个字符串对象。

    当您在准备好的语句(executeSql)中发送无效类型时,Phonegap 中使用的 Web-SQL 似乎不会出错,而是返回 0 结果。奇怪的行为,但幸运的是我能够通过解析整数来解决我的问题:

    函数 findById(id) { tx.executeSql('SELECT * FROM LOCATIONS WHERE id = ?', [ parseInt(id) ], function(tx, results) { ... } }

    【讨论】:

      【解决方案2】:

      Results 是一个对象,而不是一个数组。例如,如果您想访问名称值,请执行results.rows.item(0).name。其他列也是如此。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2015-07-18
        • 2021-09-29
        • 1970-01-01
        • 1970-01-01
        • 2013-01-07
        • 2020-06-23
        相关资源
        最近更新 更多