Escaping a single quote when using JdbcTemplate

这一生的挚爱 提交于 2019-12-10 14:29:57

问题


We're using JdbcTemplate to modify our underlying Oracle database. We're doing this by way of the update(String sql) method.

The code looks somehow like the following:

String name = "My name's yellow";
String sql = "update FIELD set NAME = '" + name "' where ID = 10
jdbcTemplate.update(sql);

This causes the error:

java.sql.SQLException: ORA-00933: SQL command not properly ended

The problem is the unescaped ' in the name variable.

What's the most convenient and correct way to escape this character?


回答1:


Use PreparedStatement. That way you nominate a placeholder and the JDBC driver will perform this correctly by sending the database the statement, plus the parameters as arguments.

    String updateStatement =
    "update " + dbName + ".COFFEES " +
    "set TOTAL = TOTAL + ? " +
    "where COF_NAME = ?";

    PreparedStatement updateTotal = con.prepareStatement(updateStatement);
    updateTotal.setInt(1, e.getValue().intValue());
    updateTotal.setString(2, e.getKey());

The question marks in the above represent the placeholders.

Because these values get passed as parameters, you don't have problems with quoting, and it protects you against SQL injection too.




回答2:


Try for name :

if ( name.contains("'") ){
    name.replaceAll("'", "''");
}


来源:https://stackoverflow.com/questions/11956451/escaping-a-single-quote-when-using-jdbctemplate

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