Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is more safe from SQL injection-NamedParameterJdbcTemplate or SimpleJdbcTemplate?

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?

like image 983
Mahesh Narayanan Avatar asked Dec 25 '22 02:12

Mahesh Narayanan


2 Answers

Both use Preparedstatements 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)

like image 126
Koos Gadellaa Avatar answered Dec 28 '22 07:12

Koos Gadellaa


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().

like image 24
chimmi Avatar answered Dec 28 '22 07:12

chimmi