【问题标题】:Android SQLite Cursor out of bounds exception on SELECT count(*) FROM tableAndroid SQLite Cursor out of bounds exception on SELECT count(*) FROM table
【发布时间】:2011-03-06 20:58:39
【问题描述】:

以下函数给了我一个越界异常...

public void count(){
    SQLiteDatabase db = table.getWritableDatabase();
    String count = "SELECT count(*) FROM table";
    Cursor mcursor = db.rawQuery(count, null);
    int icount = mcursor.getInt(0);
    System.out.println("NUMBER IN DB: " + icount);
}

这意味着返回数据库中的行数。有谁知道怎么了?我是否可能以错误的方式执行此任务?

【问题讨论】:

    标签: java android sqlite


    【解决方案1】:

    你错过了

    mcursor.moveToFirst();
    
    public void count(){
        SQLiteDatabase db = table.getWritableDatabase();
        String count = "SELECT count(*) FROM table";
        Cursor mcursor = db.rawQuery(count, null);
        mcursor.moveToFirst();
        int icount = mcursor.getInt(0);
        System.out.println("NUMBER IN DB: " + icount);
    }
    

    但是你应该使用更好的方法来完成这个任务,比如 DatabaseUtils 的内置助手

    比如

    public long count() {
        return DatabaseUtils.queryNumEntries(db,'tablename');
    }
    

    当您使用 where 查询总计数时,您可能会发现使用 DatabaseUtils.longForQuery() 获取第一列 long 值很有帮助。它更简单,您不需要使用光标进行大量工作。

    【讨论】:

    • 艾丹,如果您认为这是正确的答案,您应该点击“打勾”标记。
    • 有趣 - 我本来希望创建一个新的光标会将其移动到第一条记录而不是“第一条之前” - 很高兴知道 Android 也添加了这个概念(我更习惯于只有一个“在最后”)。也想知道,这样做(我希望如此)或SELECT * FROM table 然后getCount() 在结果光标上更好?
    • @J-16 SDiZ 您只能在 15 分钟后将答案标记为已接受。 @Joubarc 可能 DatabaseUtils 比您使用 getCount(); 执行的代码更优化;
    • DatabaseUtils 可能会得到很好的优化,但如果您已经完成查询并拥有Cursor,那么我非常怀疑调用getCount() 会更慢。跨度>
    • @Pentium10:“DatabaseUtils.queryNumEntries”仍然是一个不错的选择还是已被弃用?
    【解决方案2】:

    需要将光标移动到第一(也是唯一的)行

    Cursor mcursor = db.rawQuery(count, null);
    mcursor.moveToFirst();
    int icount = mcursor.getInt(0);
    

    【讨论】:

      【解决方案3】:

      如果您想获取特定 ID 或值的行数,可以使用它

      public int numbersOfrows (int id) {
              SQLiteDatabase db = this.getReadableDatabase();
              int numbersOfrows = 0 ;
      
              Cursor c = db.rawQuery("select count(*) from table_name where Column_name = 'yourValue'")
              if (c.moveToFirst()){
                  numbersOfrows = c.getInt(0);
              }
      
              return numbersOfrows ;
          }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-12
        • 2012-12-26
        • 1970-01-01
        • 2013-08-04
        • 1970-01-01
        • 2014-12-02
        • 2012-04-29
        • 2016-12-28
        相关资源
        最近更新 更多