使用JdbcTemplate时转义单引号

5 java oracle spring escaping jdbctemplate

我们正在使用JdbcTemplate来修改我们的底层Oracle数据库.我们是通过这种方法来做到这一点的update(String sql).

代码看起来有点如下:

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

这会导致错误:

java.sql.SQLException: ORA-00933: SQL command not properly ended
Run Code Online (Sandbox Code Playgroud)

问题是转义'name变量.

逃避这个角色最方便,最正确的方法是什么?

Bri*_*new 6

使用PreparedStatement.这样,您可以指定占位符,JDBC驱动程序将通过向数据库发送语句以及参数作为参数来正确执行此操作.

    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());
Run Code Online (Sandbox Code Playgroud)

上面的问号代表占位符.

因为这些值作为参数传递,所以引用没有问题,它也可以防止SQL注入.

  • 我可以使用JdbcTemplate的[`update(String sql,Object [] args)`](http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/jdbc/core/JdbcTemplate.html #update%28java.lang.String,%20java.lang.Object []%29)自动执行此操作的方法. (2认同)