如何查询列表< String>在jdbctemplate中 [英] how to query for a list<String> in jdbctemplate
问题描述
我正在使用spring jdbctemplate并运行如下查询:
I'm using springs jdbctemplate and running a query like below:
SELECT COLNAME FROM TABLEA GROUP BY COLNAME
没有传递任何命名参数,但是,用户将传递列名 COLNAME
。
There are no named parameters being passed, however, column name, COLNAME
, will be passed by the user.
问题
-
有吗如何为列名提供占位符,例如
?
?例如SELECT? FROM TABLEA GROUP BY?
如果我想简单地运行上述查询并获得 List<字符串>
最好的方法是什么?
If I want to simply run the above query and get a List<String>
what is the best way?
目前我正在做:
List <Map<String, Object>> data = getJdbcTemplate().queryForList(query);
for (Map m : data)
System.out.println(m.get("COLNAME"));
推荐答案
有没有办法有占位符,比如?列名?例如SELECT? FROM TABLEA GROUP BY?
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;
如果我想简单地运行上面的查询并得到一个List是最好的方法吗?
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);
}
});
编辑:要停止SQL注入,请检查colName中的非单词字符:
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
}
这篇关于如何查询列表< String>在jdbctemplate中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!