SQLite Query in Android to count rows SQLite Query in Android to count rows sqlite sqlite

SQLite Query in Android to count rows


DatabaseUtils.queryNumEntries (since api:11) is useful alternative that negates the need for raw SQL(yay!).

SQLiteDatabase db = getReadableDatabase();DatabaseUtils.queryNumEntries(db, "users",                "uname=? AND pwd=?", new String[] {loginname,loginpass});


@scottyab the parametrized DatabaseUtils.queryNumEntries(db, table, whereparams) exists at API 11 +, the one without the whereparams exists since API 1. The answer would have to be creating a Cursor with a db.rawQuery:

Cursor mCount= db.rawQuery("select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass +"'", null);mCount.moveToFirst();int count= mCount.getInt(0);mCount.close();

I also like @Dre's answer, with the parameterized query.


Use an SQLiteStatement.

e.g.

 SQLiteStatement s = mDb.compileStatement( "select count(*) from users where uname='" + loginname + "' and pwd='" + loginpass + "'; " );  long count = s.simpleQueryForLong();