zoukankan      html  css  js  c++  java
  • how to query for a list<String> in jdbctemplate?--转载

    原文地址: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
              }

     

  • 相关阅读:
    Chapter 14 高级I/O
    UNP总结 Chapter 3 套接字编程简介
    UNP总结 Chapter 1 简介
    Chapter 13 守护进程
    Chapter 17 高级进程间通信
    Chapter 15 进程间通信
    实例详解JSP内置对象
    一个记录程序运行时间表的控件
    .Grove—— .Net下的ORM框架
    .Net 下的Wondows窗体常用项目
  • 原文地址:https://www.cnblogs.com/davidwang456/p/5056703.html
Copyright © 2011-2022 走看看