iaindownie
iaindownie

Reputation: 1056

Apostrophe in SQLite select query

I have a problem with SQLite and a bit of bespoke SQL:

public Cursor getExistingSpeciesDetails(String sub_id, String english_name) {
    Cursor c = mDb.rawQuery(
            "SELECT mobileobs.how_many, mobileobs.comment, mobileobs.sensitive, "
                    + "mobileobs.breeding_evidence from mobileobs "
                    + "WHERE mobileobs.sub_id = '" + sub_id
                    + "' and mobileobs.english_name = '" + english_name
                    + "'", null);
    return c;
}

My problem is an apostrophe in the english name (Cetti's Warbler) is causing an error in the SQL (force closing my Android app). Is there any way to escape the apostrophe in this type of clause?

Thanks in advance

Upvotes: 1

Views: 2462

Answers (1)

waqaslam
waqaslam

Reputation: 68177

For that purpose you need to use SQLIte's parameter injections. For example:

Cursor c = mDb.rawQuery(
            "SELECT mobileobs.how_many, mobileobs.comment, mobileobs.sensitive, "
             + "mobileobs.breeding_evidence from mobileobs "
             + "WHERE mobileobs.sub_id = ? AND mobileobs.english_name = ?"
             , new String[]{sub_id, english_name});

Or change your input parameter as below:

Cetti''s Warbler

Upvotes: 8

Related Questions