Spring JDBC 接口学习

[b]org.springframework.jdbc.core.PreparedStatementCreator[/b]
用JdbcTemplate提供的Connection创建PreparedStatement对象,子类需要提供SQL以及为PreparedStatement对象设置必要的参数。
[code]
PreparedStatementCreator psc = new PreparedStatementCreator(){
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
         PreparedStatement pstmt = con.prepareStatement("select * from user where name=? and age=?");
         pstmt.setString(1, "lsy");
pstmt.setInt(2, 24);
         return pstmt;
      }

};
[/code]
[b]接口org.springframework.jdbc.core.PreparedStatementSetter[/b]
用于PrepraredStatement对象动态设置参数,PrepraredStatement对象由JdbcTemplate对象创建。
[code]
jdbcTemplate.update("INSERT INTO USER VALUES(?, ?, ?, ?)",
new PreparedStatementSetter() {
public void setValues(PreparedStatement ps) throws SQLException {
ps.setString(1, id);
ps.setString(2, name);
ps.setString(3, sex);
ps.setInt(4, age);
}
});
[/code]
[b]org.springframework.jdbc.core.RowCallbackHandler[/b]
用于处理查询结果,获得ResultSet对象里的数据。
[code]
final User user = new User();
jdbcTemplate.query("SELECT * FROM USER WHERE user_id = ?",
new Object[] {id},
new RowCallbackHandler() {
public void 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"));
}
});
[/code]
[b]org.springframework.jdbc.core.RowMapper[/b]
用于处理查询结果,获得ResultSet对象里的数据,把每一行的数据放在一个DTO对象里,然后由JdbcTemplate对象把所有DTO对象放在一个List。
[code]
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;
}
}
String sql = "SELECT * FROM USER";
jdbcTemplate.query(sql, new RowMapperResultReader(new UserRowMapper()));
[/code]
[b]org.springframework.jdbc.core.ResultSetExtractor[/b]
需要执行ResultSet.next()方法。
[code]
ResultSetExtractor rse = new ResultSetExtractor(){
public Object extractData(ResultSet rs) throws SQLException, DataAccessException {
         List list = new ArrayList();
         while(rs.next()) {
            list.add(new String[]{rs.getString("user_id"), rs.getString("name")});
         }
         return list;
      }
};
[/code]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值