SQLite count example

本秂侑毒 提交于 2019-12-01 08:53:15
Harry Joy

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!