Spring JdbcTemplate 使用总结

1、查询Object

    public Classify queryClassifById(int id){
        String sql="select * from t_classify where id=?";
        Object[] args = new Object[] { id };
        Classify classify = jdbcTemplate.queryForObject( sql, args, ParameterizedBeanPropertyRowMapper.newInstance(Classify.class));
        return classify;
    }

2、查询List

    public List<Classify> getAllMenu(){
        String sql="select * from t_classify";
        List<Classify> list = jdbcTemplate.query( sql, ParameterizedBeanPropertyRowMapper.newInstance(Classify.class));
        return list;
    }

3、查询记录数

    public int getCount(){
        String sql="select count(*) from t_classify";
        return jdbcTemplate.queryForInt(sql);
    }

4、获得自增长主键

    public int insert(final News news) {
        final String sql = "insert into t_news(title, content)"
                + " values(?,?)";
        KeyHolder keyHolder=new GeneratedKeyHolder();
        jdbcTemplate.update(new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection conn)
                    throws SQLException {
                PreparedStatement ps=conn.prepareStatement(sql);
                ps.setString(1, news.getTitle());
                ps.setString(2, news.getContent());return ps;
            }
        },keyHolder);
        return keyHolder.getKey().intValue();
    }

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。