Using prepared statements with JDBCTemplate Using prepared statements with JDBCTemplate java java

Using prepared statements with JDBCTemplate


By default, the JDBCTemplate does its own PreparedStatement internally, if you just use the .update(String sql, Object ... args) form. Spring, and your database, will manage the compiled query for you, so you don't have to worry about opening, closing, resource protection, etc. One of the saving graces of Spring. A link to Spring 2.5's documentation on this. Hope it makes things clearer. Also, statement caching can be done at the JDBC level, as in the case of at least some of Oracle's JDBC drivers. That will go into a lot more detail than I can competently.


class Main {    public static void main(String args[]) throws Exception {        ApplicationContext ac = new          ClassPathXmlApplicationContext("context.xml", Main.class);        DataSource dataSource = (DataSource) ac.getBean("dataSource");// DataSource mysqlDataSource = (DataSource) ac.getBean("mysqlDataSource");        JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);        String prasobhName =         jdbcTemplate.query(           "select first_name from customer where last_name like ?",            new PreparedStatementSetter() {              public void setValues(PreparedStatement preparedStatement) throws                SQLException {                  preparedStatement.setString(1, "nair%");              }            },             new ResultSetExtractor<Long>() {              public Long extractData(ResultSet resultSet) throws SQLException,                DataAccessException {                  if (resultSet.next()) {                      return resultSet.getLong(1);                  }                  return null;              }            }        );        System.out.println(machaceksName);    }}


Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {    @Override    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {        PreparedStatement updateSales = con.prepareStatement(        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");        updateSales.setInt(1, 75);         updateSales.setString(2, "Colombian");         return updateSales;    }};