Abhishek Singh
Abhishek Singh

Reputation: 9745

How to use prepared statement that returns resultset with jdbcTemplate in spring mvc 3?

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.

Upvotes: 2

Views: 8659

Answers (1)

JB Nizet
JB Nizet

Reputation: 691685

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.

Upvotes: 2

Related Questions