5

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?

2 Answers 2

6

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.

1
0

Try for name :

if ( name.contains("'") ){
    name.replaceAll("'", "''");
}
1
  • This is an optional solution that is working but not the best solution. Best way is to parameterize the SQL statement to handle all cases as written on other answers. Commented Nov 30, 2018 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.