JDBC的query获取list集合

时间:2021-10-22 21:15:19
    JdbcTemplate 提供以下主要方法简化JDBC操作:

    List query(String sql,Ojbect[] args,RowMapper rowMapper)

    说明:常用的查询,sql待执行的sql语句,args是sql语句的参数,rowMapper负责将每一行记录转化为java对象存放在list,并最终返回,例如:
    Java代码  收藏代码

    public List<Book> queryByAuthor(String author) {  
            String sql = "select * from book where author=?";  
            Collection c = getJdoTemplate().find(sql,  
                    new Object[] { author },new BookRowMapper());  
            List<Book> books = new ArrayList<Book>();  
            books.addAll(c);  
            return books;  
    }  
      
    class BookRowMapper implements RowMapper{  
         public Object mapRow(ResultSet res, int index) throws SQLException {  
              Book book = new Book();  
              book.setId(rs.getInt("id"));  
              //省略set  
           return book;  
        }  
    } 



摘取至:http://ari.iteye.com/blog/618449

相关文章