How to escape single quotes for SQL insert…when string to insert is in a user generated variable

前端 未结 3 1194
无人及你
无人及你 2020-12-05 23:48

I am building an insert command to execute using jdbc. Part of it is to concatenate a user generated string...this all works until the user uses a string like this:

3条回答
  •  臣服心动
    2020-12-06 00:41

    Here's another option:

    Use a native Android method designed for exactly this purpose:

    DatabaseUtils.sqlEscapeString(String)
    

    Here is the documentation for it online:

    • sqlEscapeString() on Android Developers

    The main advantage of using this method, in my opinion, is the self-documentation because of the clear method name.


    String userString="a'bcd";
    String insertTableSQL = "INSERT INTO myTable "
                                + "(insertColumn) " 
                                + "VALUES("
                                    +"'"+DatabaseUtils.sqlEscapeString(userString)+"'"
                                    +")";
    
    statement.executeUpdate(insertTableSQL);
    

提交回复
热议问题