This is another debated subject, but this time i am searching only for the simple and documented answers. The scenario :
Let\'s assume the following method:
You can significantly reduce the amount of boilerplate JDBC code by using Spring-JDBC instead of plain-old JDBC. Here's the same method rewritten using Spring-JDBC
public static Hashtable getSomeDogs(String colName, String colValue) {
StringBuffer sql = new StringBuffer();
sql.append("SELECT * FROM ").append("dogs_table");
sql.append(" WHERE ").append(colName).append("='");
sql.append(colValue).append("'");
Hashtable result = new Hashtable();
RowMapper mapper = new RowMapper() {
public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
Dogs dog = new Dogs();
//...initialize the dog from the current resultSet row
result.put(new Long(dog.getId()), dog);
}
};
(Hashtable) jdbcTemplate.queryForObject(sql, mapper);
}
Spring takes care of:
As others have mentioned you really should use a PreparedStatement to construct the SQL instead of a String (or StringBuffer). If for some reason you can't do this, you could improve the readability of the query by constructing the SQL like this instead:
String sql =
"SELECT * FROM dogs_table " +
"WHERE " + "colName" + " = '" + colValue + "'";