JdbcTemplate 常用方法
JdbcTemplate 常用方法
update:
实现增删改
//update方法 (增 删 改) @Override public void add(Users user) { String sql = "insert into users values(null,?,?)"; jdbcTemplate.update(sql, user.getUname(), user.getPassword()); }
queryForObject:
查询的结果是一个对象或单个值
//测试 根据id号查询 public Users selectUsersById(int uid) { String sql="select * from users where uid=?"; //查询 单行数据 Users user= jdbcTemplate.queryForObject(sql, new Object[]{uid}, new RowMapper<Users>() { @Override public Users mapRow(ResultSet resultSet, int i) throws SQLException { return rowMapHandler(resultSet); } }); return user; }
//自己组装对象 public Users rowMapHandler(ResultSet resultSet) throws SQLException { Users user=new Users(); user.setUid(resultSet.getInt("uid")); user.setUname(resultSet.getString("uname")); user.setPassword(resultSet.getString("password")); return user; }
查询的结果是一个数值
public int selectUsersCount() { String sql = "select count(*) from users"; int num = jdbcTemplate.queryForObject(sql, Integer.class); return num; } query //查询 返回集合 public List<Users> selectUsers() { String sql = "select * from users"; List<Users> usersList= jdbcTemplate.query(sql, new RowMapper<Users>() { //遍历结果集 将结果集中的每条数据 组装成Users对象 @Override public Users mapRow(ResultSet resultSet, int i) throws SQLException { return rowMapHander(resultSet); } }); return usersList; }
//自己组装对象
public Users rowMapHander(ResultSet resultSet) throws SQLException { Users user=new Users(); user.setUid(resultSet.getInt("uid")); user.setUname(resultSet.getString("uname")); user.setPassword(resultSet.getString("password")); return user; }