Error when trying to find if a value exists in sqlite database
Question
I am new to using SQLite databases and android mobile development. I am trying to check if the username entered by a edit text field exists in the database. When I run it and click a button, the application crashes. This is my code.
public boolean findUsername(String username) {
Cursor c = ourDatabase.query(true, DATABASE_TABLE_L, new String[] {
KEY_USERID, KEY_USERNAME, KEY_PASSWORD,KEY_SECRETQ,KEY_ANSWER}, KEY_USERNAME + "="
+ username, null, null, null, null, null);
if (c != null) {
return true;
}
return false;
}
}
The error from the log cat states that:
no such column: bobby: , while compiling: SELECT DISTINCT userId, username, password, secretQ, answer FROM Login WHERE username=bobby
What am I doing wrong?
Solution
You should form your query like this
SELECT DISTINCT userId, username, password, secretQ, answer FROM Login WHERE username='bobby'
You have to put quotes to username.
Cursor c = ourDatabase.query(true, DATABASE_TABLE_L, new String[] {
KEY_USERID, KEY_USERNAME, KEY_PASSWORD,KEY_SECRETQ,KEY_ANSWER}, KEY_USERNAME + "='"
+ username +"'", null, null, null, null, null);
Try above.
OTHER TIPS
Cursor c = ourDatabase.query(true, DATABASE_TABLE_L, new String[] {
KEY_USERID, KEY_USERNAME, KEY_PASSWORD,KEY_SECRETQ,KEY_ANSWER}, KEY_USERNAME + "=?",
username, null, null, null, null);
Try This.
Cursor C = ourDatabase.query(DATABASE_TABLE_L, new String[] {
KEY_USERID}, KEY_USERNAME + "= ?" , new String[] {username}, null, null,null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow