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

StackOverflow https://stackoverflow.com/questions/19489978

  •  01-07-2022
  •  | 
  •  

Pergunta

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.

Foi útil?

Solução

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.
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top