java SELECT count(*) FROM表上的Android SQLite Cursor越界异常
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3094257/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Android SQLite Cursor out of bounds exception on SELECT count(*) FROM table
提问by Skizit
The following function is giving me an out of bounds exception...
以下函数给了我一个越界异常......
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);
}
It's meant to return the number of rows in the database. Anybody know whats wrong? am I perhaps doing this task the wrong way?
它旨在返回数据库中的行数。有谁知道怎么了?我是否可能以错误的方式执行此任务?
回答by Pentium10
You missed out
你错过了
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);
}
But you should use better methods for this task, like the inbuilt helpers of DatabaseUtils
但是你应该使用更好的方法来完成这个任务,比如 DatabaseUtils 的内置助手
such as
如
public long count() {
return DatabaseUtils.queryNumEntries(db,'tablename');
}
You might find helpful to use DatabaseUtils.longForQuery()to get the first column long value, when you have where query for the total count. It's simpler and you do not need that bunch of work with the Cursor.
DatabaseUtils.longForQuery()当您对总计数进行 where 查询时,您可能会发现用于获取第一列 long 值很有帮助。它更简单,您不需要使用 Cursor 进行那么多工作。
回答by JoshP
need to move the cursor to the first (and only) row
需要将光标移动到第一(也是唯一)行
Cursor mcursor = db.rawQuery(count, null);
mcursor.moveToFirst();
int icount = mcursor.getInt(0);
回答by Mohamed Hussien
you can use this if you want to get Number of Rows for Specific ID or Value
如果您想获取特定 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 ;
}

