首页 > 代码库 > Spring JdbcTemplate 使用总结

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();    }

 

Spring JdbcTemplate 使用总结