BekaBot
BekaBot

Reputation: 510

Select statement in SQLite does not return result

Then the following must return the password of the user stored in the DB

public String getPasswordByUsername(String userName)
{
    SQLiteDatabase db = this.getReadableDatabase();

    String selectQuery = "SELECT  * FROM " + TABLE_USERS + " WHERE "
            + KEY_USERS_USERNAME + " = " + userName;

    Cursor cursor = db.rawQuery(selectQuery, null);
    if (cursor.getCount() < 1) {
        cursor.close();
        return "NOT EXIST";
    }

    cursor.moveToFirst();
    String password = cursor.getString(cursor.getColumnIndex("password"));
    cursor.close();
    return password;
}

When I try to get the password of the user "w", I get:

12-24 10:54:23.639: E/AndroidRuntime(11237): FATAL EXCEPTION: main
12-24 10:54:23.639: E/AndroidRuntime(11237): Process: com.example.doit, PID: 11237
12-24 10:54:23.639: E/AndroidRuntime(11237): android.database.sqlite.SQLiteException: no such column: w (code 1): , while compiling: SELECT  password FROM users WHERE username = w

Here is what is stored in DB: enter image description here

How can I fetch the right password? Thank you.

Upvotes: 1

Views: 1454

Answers (4)

Kishan patel
Kishan patel

Reputation: 214

change to this simple formate:-

String dateQuery = "SELECT * FROM user where username='" + USERNAME+"'";

Cursor data = db.rawQuery(dateQuery, null);

i think its helpfull .

Upvotes: 1

petey
petey

Reputation: 17140

The correct way would be to pass username into the selectionArgs in rawQuery's 2nd param/arg, example:

String selectQuery = "SELECT  * FROM " + TABLE_USERS + " WHERE "
        + KEY_USERS_USERNAME + " =  ?";

Cursor cursor = db.rawQuery(selectQuery, new String[]{ username });

This way if your username value is w or even "w' it will be properly escaped in your resulting sql statement that is executed.

Upvotes: 1

IAmGroot
IAmGroot

Reputation: 13855

Change to this: (include quotes)

String selectQuery = "SELECT  * FROM " + TABLE_USERS + " WHERE "
        + KEY_USERS_USERNAME + " = '" + userName + "'";

At the moment you are creating an SQL string with no quotes, so it is not treated as a string, and instead is treating it as a column name. which does not exist.

Upvotes: 1

Kenan Begić
Kenan Begić

Reputation: 1228

Change " = " + userName to : " = '" + username+ "'"

Upvotes: 3

Related Questions