2010-06-22 33 views
13

下面的函数给我一个出界异常越界异常的...的Android SQLite的光标出来SELECT COUNT(*)FROM表

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); 
} 

这意味着要返回数据库的行数。任何人都知道什么是错的?我是否可能以错误的方式完成这项任务?

回答

48

你错过了

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'); 
} 

您可能会发现有助于使用DatabaseUtils.longForQuery()获取第一列的长整数值,当你有查询总数的地方。这很简单,你不需要使用Cursor这么多的工作。

+0

这工作的数量,你可以利用这一点,谢谢:) – Skizit 2010-06-22 14:50:00

+0

艾丹,如果你觉得这是正确的答案,你应该点击“打勾”标记。 – 2010-06-22 14:55:07

+0

有趣的 - 我会期望创建一个新的光标将它移动到第一个记录,而不是“第一个之前” - 很好的知道Android也增加了这个概念(我更习惯于只有一个“最后一个”)。想知道的是,有什么更好的,做到这一点(我期望如此),或者'SELECT * FROM table',然后getCount()'在结果光标上? – Joubarc 2010-06-22 14:56:52

3

需要将光标移动到第一个(也是唯一一个)排

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

,如果你想获得行的具体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 ; 
    }