User user = jdbcTemplate.query(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection conn)
throws SQLException {
String sql = "select * from tb_user where id=?";
PreparedStatement ps = conn.prepareStatement(sql);
return ps;
}
}, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
ps.setInt(1, 3);
}
}, new ResultSetExtractor<User>() {
@Override
public User extractData(ResultSet rs) throws SQLException,
DataAccessException {
User user = new User();
user.setUsername(rs.getString("username"));
return user;
}
});
测试使用上面这个方法发现一直报这个错误:
org.springframework.dao.TransientDataAccessResourceException: PreparedStatementCallback; SQL []; Before start of result set; nested exception is java.sql.SQLException: Before start of result set
后来发现:
java.sql.SQLException: Before start of result set
(2010-12-21 13:47:23)
加上while(rs.next()){
//代码
}
一切OK