How to escape unsupported character in SQLite on Android?

前端 未结 3 2002
面向向阳花
面向向阳花 2020-12-29 06:34

can anybody tell How to escape or replace not supported character like single quotes in sqlite in android can anybody give example

Thanks

相关标签:
3条回答
  • 2020-12-29 07:08

    You can utilize the commons-lang utility or you can use a regexp to handle it.

    If you're building dynamic SQL, what I would suggest is trying to use a prepared statement which would eliminate the need for escaping single quotes.

    Using just a dynamic SQL built using string concatenation:

    String value = "one's self";
    StringBuilder query= new StringBuilder();
    query.append("insert into tname(foo) values (").append(value).append(")");
    ... execute call with query.toString() ...
    

    Change that to

    String value = "one's self";
    value= DatabaseUtils.sqlEscapeString(value);
    StringBuilder query= new StringBuilder();
    query.append("insert into tname(foo) values (").append(value).append(")");
    ... execute call with query.toString() ...
    

    Ideally, use a prepared statement

    String value = "one's self";
    StringBuilder query= StringBuilder();
    query.append("insert into tname(foo) values (?)");
    SQLiteStatement stmt= db.compileStatement(query.toString());
    stmt.bindString(1, value);
    long rowId= stmt.executeInsert();
    // do logic check for > -1 on success
    

    This way you don't run into "SQL injection attacks".

    Refer to http://developer.android.com/reference/android/database/sqlite/SQLiteStatement.html for more information.

    EDIT I did a little more digging, you can use DatabaseUtils.sqlEscapeString(String) to escape the content of a string so that it is valid for a complete SQL statement with no prepares.

    0 讨论(0)
  • 2020-12-29 07:12

    Aren't these done with a simple \? So, your single quote would be \'.

    0 讨论(0)
  • 2020-12-29 07:15

    Actually, the simpliest way is to replace single quotes (') with two-single quotes (''). Your query will then become:

    insert into tname(foo) values ('one''s self');
    

    Explanation: SQLite advocates the use of single quotes (') instead of double quotes (") as string delimiters, claiming that this is what the SQL standard requires (I was unable to confirm this). SQLite also differs from all other SQL databases I know, in that it uses '' instead of \' , again, claiming SQL standards. (Again, I was unable to confirm this claim).

    Personally, I tend to disagree with that claim, since every other SQL database I know uses the C way of escaping chars, backslash. Even if it was written to use '' somewhere in ISO's SQL standard, I believe it might be best to revise that standard to use the C way, because in practice, it already is the standard anyway.

    Please note that:

    insert into tname(foo) values ('ones "self"');
    

    is a valid sql statement by that logic, and requires no additional escaping.

    0 讨论(0)
提交回复
热议问题