How to query for a List<String> in JdbcTemplate? How to query for a List<String> in JdbcTemplate? java java

How to query for a List<String> in JdbcTemplate?


To populate a List of String, you need not use custom row mapper. Implement it using queryForList.

List<String>data=jdbcTemplate.queryForList(query,String.class)


Use following code

List data = getJdbcTemplate().queryForList(query,String.class)


Is there a way to have placeholders, like ? for column names? For example SELECT ? FROM TABLEA GROUP BY ?

Use dynamic query as below:

String queryString = "SELECT "+ colName+ " FROM TABLEA GROUP BY "+ colName;

If I want to simply run the above query and get a List what is the best way?

List<String> data = getJdbcTemplate().query(query, new RowMapper<String>(){                            public String mapRow(ResultSet rs, int rowNum)                                                          throws SQLException {                                    return rs.getString(1);                            }                       });

EDIT: To Stop SQL Injection, check for non word characters in the colName as :

          Pattern pattern = Pattern.compile("\\W");          if(pattern.matcher(str).find()){               //throw exception as invalid column name          }