Spring JDBC Framework simplifies the use of JDBC and helps to avoid common errors.
The following example shows using RowCallbackHandler interface.
This callback interface is called once for processing each row. The CustomRowCallbackHandler
given in this examples buffers the user names from each row.
/**
* Initialize context and get the JdbcTemplate
*/
ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");
DataSource dataSource = (DataSource) appContext.getBean("dataSource");
JdbcTemplate template = new JdbcTemplate(dataSource);
CustomRowCallbackHandler handler = new CustomRowCallbackHandler();
template.query("select * from USER", handler);
System.out.println("Names : " + handler.getUserNames());
}
}
//RowCallbackHandler is stateful class CustomRowCallbackHandler implements RowCallbackHandler {
private StringBuilder sb = new StringBuilder();
@Override public void processRow(ResultSet rs) throws SQLException { if (sb.length() != 0) {
sb.append(", ");
}
sb.append(rs.getString("NAME"));
}
public String getUserNames() { return sb.toString();
}
}