日期:2014-05-16  浏览次数:20499 次

Spring 中的JdbcTemplate使用

1.JdbcTemplate的execute()方法执行SQL DDL语句,例如:

jdbcTemplate.execute("CREATE TABLE USER (user_id integer, name varchar(100))");

使用JdbcTemplate进行查询时,可以使用queryForXXX()等方法,例如使用queryForInt()方法传回user表格中的数据数目: jdbcTemplate.quertForInt("select count(*) from user"); 也可以使用queryForObject()传回一个查询后的对象,例如传回一个String对象:

String name=(String)jdbcTemplate.queryForObject("selcet name from user where id=?",new Object[]{id},java.lang.String.class);)

单独查询某个数据并赋值给特定对象时:

??? public BaseObj getBaseObj(final int ID) {
??????? String sql = "select * from " + DB_TABLE_NAME + " where NewsId=" + ID;
??????? BaseObj obj =(BaseObj) getJdbcTemplate().query(sql,new ResultSetExtractor(){
??????????? public Object extractData(ResultSet rs) throws SQLException,DataAccessException {
??????????????? if (rs.next()) {
??????????????????? NewsObj news = new NewsObj();
??????????????????? news.setID(rs.getInt("NewsID"));
??????????????????? news.setTitle(rs.getString("NewsTitle"));
??????????????????? news.setBigClass(rs.getInt("BigClassId"));
??????????????????? news.setNewsContent(rs.getString("NewsContent"));
??????????????????? news.setNewsKey(rs.getString("NewsKey"));
??????????????????? news.setNewsAuthor(rs.getString("NewsAuthor"));
??????????????????? news.setImg(rs.getBoolean("isImg"));
??????????????????? news.setNewsFrom(rs.getString("NewsFrom"));
??????????????????? return news;
??????????????? }
??????????????? return null;
??????????? }
??????? });
?????? return obj;

??? }

上面两个例子都是传回单独一笔数据,如果要传回多笔数据,则可以使用queryForList()方法

例如:
List rows=jdbcTemplate().queryForList("select * from user where id="+id.intValue()); 传回的list中包括的是map对象,每个map对象代表查询结果中的一笔数据,每笔数据包括多个字段,要取得字段中的值,就要使用字段名作为key,
例如:
??? Iterator it=rows.iterator();
??? while(it.hasNext()){
??????? Map result=(Map)it.next();
??????? System.out.println(userMap.get("id"));
??????? System.out.println(userMap.get("name"));
??????? System.out.println(userMap.get("age"));
???? }

在查询的同时,你可以在返回结果之前先进行一些处理,这就要实现RowCallbackHandler接口

public User find(Integer id){
??? final User user=new User();
??? jdbcTemplate.query("select * from user where id=?",new Object[]{id},
???????????????????????????????????? new RowCallBackHandler(){
?????????????????????????????????????????? public void proccessRow(ResultSet rs){
???????????????????????????????????????????????? user.setId(new Integer(rs.getInt("id")));
???????????????????????????????????????????????? uset.setName(rs.getString("name"));???
??????????????????????????????????????????? }});
??? return user;
}

如果一次要返回多个查询结果对象,则可以实现RowMapper接口

public class UserRowMapper implements RowMapper{
??????? public Object MapRow(ResultSet rsmint rowNum) throws SQLException{
??????????????? User user=new User();
??????????????? user.setId(new Integer(rs.getInt("id")));
??????????????? user.setName(rs.getString("name"));
??????????????? return user;
?????? }
}

使用RowMapper查询单笔数据