final String id = user.getId(); final String name = user.getName(); final String sex = user.getSex() +""; finalint age = user.getAge(); jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)", new PreparedStatementSetter() ...{ publicvoid setValues(PreparedStatement ps) throws SQLException ...{ ps.setString(1, id); ps.setString(2, name); ps.setString(3, sex); ps.setInt(4, age); } });
final User user =new User(); jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?", new Object[] ...{id}, new RowCallbackHandler() ...{ publicvoid processRow(ResultSet rs) throws SQLException ...{ user.setId(rs.getString("user_id")); user.setName(rs.getString("name")); user.setSex(rs.getString("sex").charAt(0)); user.setAge(rs.getInt("age")); } });
class UserRowMapper implements RowMapper ...{ public Object mapRow(ResultSet rs, int index) throws SQLException ...{ User user =new User(); user.setId(rs.getString("user_id")); user.setName(rs.getString("name")); user.setSex(rs.getString("sex").charAt(0)); user.setAge(rs.getInt("age")); return user; } } public List findAllByRowMapperResultReader() ...{ String sql ="SELECT * FROM USER"; return jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper())); }
在getUser(id)里面使用UserRowMapper
public User getUser(final String id) throws DataAccessException ...{ String sql ="SELECT * FROM USER WHERE user_id=?"; final Object[] params =new Object[] ...{ id }; List list = jdbcTemplate.query(sql, params, new RowMapperResultReader(new UserRowMapper())); return (User) list.get(0); }
public Object mapRow(ResultSet rs, int arg1) throws SQLException ...{ int表当前行数 person.setId(rs.getInt("id")); } List template.query("select * from web_person where id=?",Object[],RowMapper);