Apostrophe in SQLite select query

99封情书 提交于 2020-01-25 05:42:04

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/12561173/apostrophe-in-sqlite-select-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!