1 方法 queryForObject() 与queryForList()
方法queryForObject(),当在数据表查找的记录不存在时,将抛异常,使用时需要添加异常处理,根据异常类型确定返回结果,建议使用queryForList()替代.
2 方法 update(sql,new Object[]{} ) 与 jdbcTemplate.update(sql, new PreparedStatementSetter())
在spring中第一中方式最终将转换为第二种去执行,传说第二种效率更高,未经验证. 这里只讲述这两种方式的使用,不考虑效率问题.
final String sql = "insert into t_user(c_openid, c_cellphone, c_password) values(?,?,?)";
int rowsAffected = jdbcTemplate.update(sql, new PreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps) throws SQLException {
int index = 0;
ps.setString(++index, registerData.getOpenid());
ps.setString(++index, registerData.getCellphone());
ps.setString(++index, registerData.getPassword());
}
});
final String sql = "insert into t_user(c_openid, c_cellphone, c_password) values(?,?,?)";
int rowsAffected = jdbcTemplate.update(sql, new Object[]{
registerData.getOpenid(),
registerData.getCellphone(),
registerData.getPassword()
});
3 插入返回主键
KeyHolder keyHolder = new GeneratedKeyHolder();
final String sql = "insert into t_user(c_openid, c_cellphone, c_password) values(?,?,?)";
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public java.sql.PreparedStatement createPreparedStatement(Connection con)throws SQLException, DataAccessException {
// TODO Auto-generated method stub
java.sql.PreparedStatement preparedStat = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
int index = 0;
preparedStat.setString(++index, loginData.getOpenId());
preparedStat.setString(++index, loginData.getCellphone());
preparedStat.setString(++index, loginData.getPassword());
return preparedStat;
}
}, keyHolder);
BigInteger generatedId = BigInteger.valueOf(keyHolder.getKey().longValue());