【问题标题】:COUNT(*) in Web SQL is not workingWeb SQL 中的 COUNT(*) 不起作用
【发布时间】:2013-06-29 14:31:15
【问题描述】:

我正在使用以下代码来获取emp表中的记录数,代码如下:

var myDb = initDB();  
    myDb.transaction(function(trans) {  
    var query = "SELECT COUNT(*) AS c from emp";  
        trans.executeSql(query, [], function(trans, res) {  
           var count = res.rows[0].c;  
           console.log("--- After Count ---"+count);  
     }, errorHandler); });

The query is giving error : Uncaught TypeError: Cannot read property 'c' of undefined.  
How to solve this issue?
Appreciate any help.

【问题讨论】:

  • 查询似乎执行正确,问题似乎是res.rows[0].c。不确定rows[0] 正在返回什么类型,但鉴于它是行/列类型结果,您是否尝试过res.rows[0][0]
  • 我试过了... var count = res.rows[0][0];出现错误:未捕获的类型错误:无法读取未定义的属性“0”
  • 听起来你的桌子是空的...
  • 我在表中插入一条记录并从表中获取计数
  • 类似问题here 并且答案似乎将行引用为rows.item(i) 而不是row[index],您可以尝试一下。它还提到您应该使用回调,因为transaction 有延迟响应。

标签: web-sql


【解决方案1】:
html5.webdb.Count=function() {
    var db = html5.webdb.db;
  db.transaction(function (tx) {
    tx.executeSql('SELECT COUNT(*) AS c FROM yourtable', [], function (tx, r) {
      console.log( r.rows.item(0).c);
    }, function (tx, e) {
      alert ("unknown: " + e.message);
    });
  });
}

感谢 James,我在我的数据库中使用了它

【讨论】:

    【解决方案2】:

    我已经描述了下面的代码,它将始终有效以及访问 Count(*) 的正确方法

    select COUNT(*) totalCount from tableName
    

    因此您可以通过访问 totalCount 来访问返回计数

    console.log(r.rows.item(0).totalCount);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      • 2017-11-17
      • 2021-03-05
      • 1970-01-01
      • 1970-01-01
      • 2023-01-19
      • 1970-01-01
      相关资源
      最近更新 更多