views:

99

answers:

1

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
+2  A: 

You need to quote the literal strings. This should work:

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
);

Otherwise when the SQL interpreter see's

first_name=marcus

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

String[] myArguments = new String[] {first, last};
cursor = mDb.query("SELECT * FROM contacts WHERE first_name = ? AND last_name = ?;", myArguments);

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

Akusete
You sir, are correct. I never thought I would be the one to make that mistake after I read that comic a while back, but alas, I did.
omizzle