SQLite count example

雨燕双飞 提交于 2019-12-01 06:40:59

问题


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

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