Which one is safe from SQL Injection: NamedParameterJdbcTemplate or SimpleJdbcTemplate?
For Example,
String sql = "insert into db_table (associateid,comment) values(:associateId,:comments)";
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("associateId", "12345");
paramMap.put("comments", "some comments");
int rowNumber = readTemplate.update(sql, paramMap);
or
String sql = "insert into db_table (associateid,comment) values(?,?)";
int rowNumber = readTemplate.update(sql,new Object[] {"comments","some comments"} );
First one uses NamedParameterJdbcTemplate whereas 2nd one uses SimpleJdbcTemplate. In some sites its given like Both are same, in some others NamedParameterJdbcTemplate is safe. Can anyone please clear my doubts?
Both use Preparedstatement
s to execute the query. And these are what protects against sql injection. So there is no difference with regards to SQL injection.
However, if you look at the documentation for SimpleJdbcTemplate:
Deprecated.
since Spring 3.1
in favor of JdbcTemplate and NamedParameterJdbcTemplate. The JdbcTemplate and NamedParameterJdbcTemplate now provide all the functionality of the SimpleJdbcTemplate.
So you should use the NamedParameterJdbcTemplate since it's not depracated. (legacy code might still use it, however)
I believe there is no difference, because neither of them has anything to do with SQL Injection protection. It is implemeted in underlying driver`s PreparedStatement.
For eample you can look at com.mysql.jdbc.PreparedStatement#setString().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With