Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/393.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/xml/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JdbcTemplate时转义单引号_Java_Oracle_Spring_Escaping_Jdbctemplate - Fatal编程技术网

Java 使用JdbcTemplate时转义单引号

Java 使用JdbcTemplate时转义单引号,java,oracle,spring,escaping,jdbctemplate,Java,Oracle,Spring,Escaping,Jdbctemplate,我们正在使用来修改我们的底层Oracle数据库。我们是通过这种方法来做这件事的 代码看起来像以下代码: String name = "My name's yellow"; String sql = "update FIELD set NAME = '" + name "' where ID = 10 jdbcTemplate.update(sql); 这会导致以下错误: java.sql.SQLException: ORA-00933: SQL command not properly end

我们正在使用来修改我们的底层Oracle数据库。我们是通过这种方法来做这件事的

代码看起来像以下代码:

String name = "My name's yellow";
String sql = "update FIELD set NAME = '" + name "' where ID = 10
jdbcTemplate.update(sql);
这会导致以下错误:

java.sql.SQLException: ORA-00933: SQL command not properly ended
问题是
名称
变量中的
未被替换

转义此字符的最方便和最正确的方法是什么?

使用。这样,您可以指定一个占位符,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());
上面的问号代表占位符

因为这些值是作为参数传递的,所以您在引用时不会遇到问题,它也可以保护您免受攻击。

请尝试使用名称:

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

我可以使用JdbcTemplate的方法自动完成这项工作。这是一个可选的解决方案,但不是最好的解决方案。最好的方法是参数化SQL语句,以处理所有写在其他答案上的情况。