0

I am trying to check if a record exists after selecting it using a query. I have one record in the table which is 'Administrator' 'abc123' and I am trying to use the following code below:

     //Define our database variables that we will use to get our data.
    dbhelper = new DBHelper(this);
    SQLiteDatabase db = dbhelper.getReadableDatabase();

    //Define our select query here, check if username and password exists.
    String selectQuery = "SELECT * FROM " + dbTables.userTABLE +
            " WHERE " + dbTables.username +
            " = " + "'" + input_name + "'" + " AND " +
            dbTables.userpassword + " = " + "'" + input_password + "'";

    Cursor c = db.rawQuery(selectQuery, null);

    //If the raw query was successfull.
    if(c.moveToFirst()){

        Integer userID = c.getInt(0);
        String userName = c.getString(1);
        String userPassword = c.getString(2);

        boolean exists = (c.getCount() > 0);

        if( exists )
        {
            Log.d("Database", userID.toString());
            Log.d("Database", userName.toString());
            Log.d("Database", userPassword.toString());
        }
        else
        {
            Log.d("Database NO", "NO");
        }

    }

    c.close();
    db.close();

This works when the record exists however when the record doesn't exist it doesn't print anything at all. I have tried entering a different username and password that doesn't exist in the database and it doesn't seem to print anything. What am I doing wrong?

2
  • One don't select *. It will move all columns to the buffer. select only one column. 2nd don't invent your own security. Ping a service to authenticate. Commented Apr 3, 2017 at 14:18
  • This doesn't relate to your question, but use prepared statements! Your code is susceptible to SQL-injection attacks. Commented Apr 3, 2017 at 20:41

1 Answer 1

3

From docs:

Return boolean, indicating whether the move succeeded.

if (c.moveToFirst()) {
  ...
} else {
    // cursor is empty, print here
}

Obviously, if there are no records then move hasn't succeeded, you have to check it in else block.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.