VO代碼:java
public class VO4Blog { private int b_id; private int b_typeid; private String b_title; private String b_intro; private String b_content; private String b_posttime; private String b_viewnums; public int getB_id() { return b_id; } public void setB_id(int b_id) { this.b_id = b_id; } public int getB_typeid() { return b_typeid; } public void setB_typeid(int b_typeid) { this.b_typeid = b_typeid; } public String getB_title() { return b_title; } public void setB_title(String b_title) { this.b_title = b_title; } public String getB_intro() { return b_intro; } public void setB_intro(String b_intro) { this.b_intro = b_intro; } public String getB_content() { return b_content; } public void setB_content(String b_content) { this.b_content = b_content; } public String getB_posttime() { return b_posttime; } public void setB_posttime(String b_posttime) { this.b_posttime = b_posttime; } public String getB_viewnums() { return b_viewnums; } public void setB_viewnums(String b_viewnums) { this.b_viewnums = b_viewnums; } }
將VO對象放進arraylst集合的代碼:mysql
public static List<VO4Blog> doCheckConByOrder() { Connection con = null; Statement st = null; ResultSet rs = null; VO4Blog vo = null; List<VO4Blog> vols = new ArrayList<VO4Blog>(); try{ Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/myblog","root","root"); st = con.createStatement(); String sql = "select * from mb_blog order by b_posttime desc"; rs = st.executeQuery(sql); while(rs.next()) { int b_id = rs.getInt("b_id"); int b_typeid = rs.getInt("b_typeid"); String b_title = rs.getString("b_title"); String b_intro = rs.getString("b_intro"); String b_content = rs.getString("b_content"); String b_posttime = rs.getString("b_posttime"); String b_viewnums = rs.getString("b_viewnums"); //封裝對象 vo = new VO4Blog(); vo.setB_id(b_id); vo.setB_typeid(b_typeid); vo.setB_title(b_title); vo.setB_intro(b_intro); vo.setB_content(b_content); vo.setB_posttime(b_posttime); vo.setB_viewnums(b_viewnums); vols.add(vo); } }catch(Exception ex){ System.out.println(ex); }finally{ try{ if(rs!=null){ rs.close(); } if(st!=null){ st.close(); } if(con!=null){ con.close(); } }catch(Exception ex){ System.out.println(ex); } } return vols; }
定義一個List對象並調用裏面的VO對象的屬性值:sql
List<VO4Blog> vols = DBUtil.doCheckConByOrder();
因爲add()添加的是Object類型對象,可使用迭代器取出的對象也是Object,因此要強制轉換爲VO4Blog對象:post
Iterator it = vols.iterator(); while(it.hasNext()){ VO4Blog vo = (VO4Blog)it.next(); System.out.println(vo.getB_id()); }
此時才能正常打印出vo.getB_id()this
若是您路過看到,有更好的方法請多多指教,提出更好方法(謝謝!)。對象