ITPub博客

首页 > > > how to query for a list<String> in jdbctemplate?--

how to query for a list<String> in jdbctemplate?--

作者:zhmw 时间:2020-02-04 12:09:02 0 删除 编辑

原文地址:http://stackoverflow.com/questions/13354158/how-to-query-for-a-liststring-in-jdbctemplate

 

 

I'm using springs jdbctemplate and running a query like below:

SELECT COLNAME FROM TABLEA GROUP BY COLNAME

There are no named parameters being passed, however, column name, COLNAME, will be passed by the user.

Questions

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

  2. If I want to simply run the above query and get a List<String> what is the best way?

Currently I'm doing:

List <Map<String, Object>> data = getJdbcTemplate().queryForList(query);
for (Map m : data)
  System.out.println(m.get("COLNAME"));

Answers

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
          }

 

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/69901620/viewspace-3165752/ ,如需转载,请注明出处,否则将追究法律责任。

下一篇: 67895678
请登录后发表评论 登录
全部评论

注册时间:2018-12-04

  • 博文量
    295
  • 访问量
    9529