问题
I am using SQLite in Android. I have the query, query executed and how to print count from cursor.
Cursor dataCount = mDb.rawQuery("select count(*) from " + DATABASE_JOURNAL_TABLE, null);
I have no record in table.
回答1:
May be by getInt(index) as
cursor.getInt(1); // this is for example, you have to adjust index in your code
Also cursor has a built in function getCount() to return row number so can also do like this:
// assuming your table has `id` column as primary key or unique key.
Cursor dataCount = mDb.rawQuery("select id from " + DATABASE_JOURNAL_TABLE, null);
dataCount.getCount();
See android devloper's doc for Cursor for more information.
回答2:
You already have the correct approach.
Cursor cursor = database.rawQuery("select count(*) from " + DATABASE_JOURNAL_TABLE, null);
// ensure there is at least one row and one column
if (cursor.getCount() > 0 && cursor.getColumnCount() > 0) {
cursor.close();
return cursor.getInt(0);
} else {
cursor.close();
return 0;
}
You must check that there is at least 1 row and 1 column, if you provide a table that does not yet exist there will be no column to access and cursor.getInt(0) will throw an exception.
source: https://github.com/samkirton/SQLKing
来源:https://stackoverflow.com/questions/5831085/sqlite-count-example