93

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.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
arun
  • 1,001
  • 2
  • 8
  • 5

10 Answers10

124

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});
Martin Harris
  • 28,277
  • 7
  • 90
  • 101
scottyab
  • 23,621
  • 16
  • 94
  • 105
119

@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.

ghchinoy
  • 1,523
  • 1
  • 11
  • 15
62

Use an SQLiteStatement.

e.g.

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

  long count = s.simpleQueryForLong();
Teknogrebo
  • 1,247
  • 1
  • 12
  • 22
  • 1
    One thing I like about this answer vs @scottyab's answer (which IS also really good) is that you can specify a LIMIT clause in this case. This is useful when you just want to know if there are ANY rows in a table (e.g., select (count(*) > 0) from TABLE LIMIT 1) vs no rows. I'm guessing that'll be faster when the table could have no rows or a ton of rows. This is the specific case I had when searching for this... – stuckj Sep 29 '16 at 15:00
  • @Teknogrebo: This is a nice answer, though I would use the parameterized version. You can use `?`s in the query and then use `bindString(int, String)` and `bindLong(int, long)` to insert the values. See [here](https://developer.android.com/reference/android/database/sqlite/SQLiteDatabase.html#compileStatement). – DearVolt Jul 13 '17 at 06:36
23

See rawQuery(String, String[]) and the documentation for Cursor

Your DADABASE_COMPARE SQL statement is currently invalid, loginname and loginpass won't be escaped, there is no space between loginname and the and, and you end the statement with ); instead of ; -- If you were logging in as bob with the password of password, that statement would end up as

select count(*) from users where uname=boband pwd=password);

Also, you should probably use the selectionArgs feature, instead of concatenating loginname and loginpass.

To use selectionArgs you would do something like

final String SQL_STATEMENT = "SELECT COUNT(*) FROM users WHERE uname=? AND pwd=?";

private void someMethod() {
    Cursor c = db.rawQuery(SQL_STATEMENT, new String[] { loginname, loginpass });
    ...
}
Dre
  • 4,298
  • 30
  • 39
22

Assuming you already have a Database (db) connection established, I think the most elegant way is to stick to the Cursor class, and do something like:

String selection = "uname = ? AND pwd = ?";
String[] selectionArgs = {loginname, loginpass};
String tableName = "YourTable";
Cursor c = db.query(tableName, null, selection, selectionArgs, null, null, null);
int result = c.getCount();
c.close();
return result;
Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Eloi Navarro
  • 1,435
  • 1
  • 14
  • 26
  • 2
    You should at least specify a column. Passing null will return all columns, which is discouraged to prevent reading data from storage that isn't going to be used. #perfmatters – redochka Aug 10 '15 at 14:06
  • In fact if the necessary info is only a count, retrieving a single column (ID for instance) would be more than enough – Eloi Navarro Aug 10 '15 at 14:29
12

how to get count column

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

int sometotal = (int) DatabaseUtils.longForQuery(db, DATABASE_COMPARE, null);

This is the most concise and precise alternative. No need to handle cursors and their closing.

Community
  • 1
  • 1
Arif Amirani
  • 26,265
  • 3
  • 33
  • 30
  • Amazing - been working with Android since forever and never knew about this DatabaseUtils - Google should be better at promoting there utils... – slott Aug 31 '17 at 09:24
6

If you are using ContentProvider then you can use:

Cursor cursor = getContentResolver().query(CONTENT_URI, new String[] {"count(*)"},
            uname=" + loginname + " and pwd=" + loginpass, null, null);
    cursor.moveToFirst();
    int count = cursor.getInt(0);
Beshoy Fayez
  • 300
  • 5
  • 10
6

If you want to get the count of records then you have to apply the group by on some field or apply the below query.

Like

db.rawQuery("select count(field) as count_record from tablename where field =" + condition, null);
Anik Islam Abhi
  • 25,137
  • 8
  • 58
  • 80
Chirag
  • 56,621
  • 29
  • 151
  • 198
5

Another way would be using:

myCursor.getCount();

on a Cursor like:

Cursor myCursor = db.query(table_Name, new String[] { row_Username }, 
row_Username + " =? AND " + row_Password + " =?",
new String[] { entered_Password, entered_Password }, 
null, null, null);

If you can think of getting away from the raw query.

Jochen Birkle
  • 335
  • 4
  • 14
1
int nombr = 0;
Cursor cursor = sqlDatabase.rawQuery("SELECT column FROM table WHERE column = Value", null);
nombr = cursor.getCount();
4b0
  • 21,981
  • 30
  • 95
  • 142