Im trying to get an object form my SQLite database in my Android application. I know that the contact is in the database because when I add it and try finding by ID, it returns the object. When I try finding by first and last name, though, it throws an exception and Im left with a null reference. Here is the query:
cursor = mDb.query(DB_CONTACTS_NAME,
new String[] {KEY_ID, KEY_LAST_NAME, KEY_FIRST_NAME, KEY_EMAIL_ADDRESS,
KEY_ORGANIZATION_NAME, KEY_LABEL, KEY_LABEL_POSITION},
KEY_FIRST_NAME + "=" + first + " AND " + KEY_LAST_NAME + "=" + last,
null, null, null, null
);
Ive also tried to find just by first name and just by last name. Same result as above.
Edit: The exception is an SQLite exception
no such column: aurelius: , while compiling: SELECT _id, last_name, first_name,
email_address, organization_name, label, label_position FROM contacts WHERE
first_name=marcus AND last_name=aurelius
And also happens when trying to select just first or last name
no such column: marcus: , while compiling: SELECT _id, last_name, first_name,
email_address, organization_name, label, label_position FROM contacts WHERE
first_name=marcus
You need to quote the literal strings. This should work:
Otherwise when the SQL interpreter see’s
You cannot expect it to know that ‘marcus’ is not a table name or a variable.
On a side note try searching for the last name “Billy” “); drop table contacts;”
DO NOT CONSTRUCT SQL QUERIES FROM DATA STRINGS
Instead use a query which takes in an argument list. Search the docs for something like
This is much safer. In your version if the ‘first’ or ‘last’ variables contain control characters which SQLite interprets as commands then you may break your database system. DO NOT DO IT … EVER