SQLite Query in Android to count rows

arun picture arun · Mar 5, 2011 · Viewed 131.7k times · Source

I'm trying to create a simple Login form, where I compare the login id and password entered at the login screen with that stored in the database.

I'm using the following query:

final String DATABASE_COMPARE =
"select count(*) from users where uname=" + loginname + "and pwd=" + loginpass + ");" ;

The issue is, I don't know, how can I execute the above query and store the count returned.

Here's how the database table looks like ( I've manged to create the database successfully using the execSQl method)

private static final String
DATABASE_CREATE =
            "create table users (_id integer autoincrement, "
            + "name text not null, uname primary key text not null, " 
            + "pwd text not null);";//+"phoneno text not null);";

Can someone kindly guide me as to how I can achieve this? If possible please provide a sample snippet to do the above task.

Answer

scottyab picture scottyab · Jan 15, 2012

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});