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变量.
逃避这个角色最方便,最正确的方法是什么?
使用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注入.
| 归档时间: |
|
| 查看次数: |
6358 次 |
| 最近记录: |