Question

Here is my code which uses jdbcTemplate

 String SQL = "select branch from branchTable where branch_name = '" + branch + "'";         
           ArrayList<String> branchList = (ArrayList<String>) jdbcTemplateObject.query(SQL, new RowMapper() {
                  public Object mapRow(ResultSet resultSet, int i) throws SQLException {
                    return resultSet.getString("city_desc");
                  }
                });
                       return branchList;

Now i want to be able to use preparedstatement with a query like "select branch from branchTable where branch_name = ?"

How can i do that with jdbcTemplate ? Examples i searched show demonstration on how to use it with update or insert query, but not with select query..

Please help.

Was it helpful?

Solution

JdbcTemplate has another query() method which takes arguments of the prepared statement as parameter:

jdbcTemplateObject.query(SQL, new Object[] {branchName}, new RowMapper() {...});

Note that:

  • SQL should be named sql
  • You should use List and not ArrayList. Nothing in the javadoc guarantees that an ArrayList is returned. And you shouldn't care about the concrete type of list returned.
  • You should use a RowMapper<String> and not a raw RowMapper.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top