Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm using Spring's JdbcTemplate and running a query like this:

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")); } 
like image 555
birdy Avatar asked Nov 13 '12 00:11

birdy


People also ask

How do I write a JdbcTemplate query?

Override the method named deleteEmployee() that contains one parameter of type integer. The integer indicates the ID of the employee to be deleted from the database. Create a SQL string to delete the employee by ID. Call the update method of JdbcTemplate and pass the string and the ID to be bound to the query.

How do you use JdbcTemplate to find an object?

In Java's Spring framework, we can use jdbcTemplate. queryForObject() to get a single row record from the database, and convert the row into an object (i.e. POJO or your entity class) via the row mapper feature. Java's Spring framework provides class, which is most useful and also Recommended.

What is the use of queryForList?

queryForList returns a List of LinkedHashMap objects. You need to cast it first like this: List list = jdbcTemplate.


2 Answers

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) 
like image 139
Ashwinie Avatar answered Oct 05 '22 10:10

Ashwinie


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           } 
like image 34
Yogendra Singh Avatar answered Oct 05 '22 10:10

Yogendra Singh