创建对象在while循环里面和外面的不同效果
1.在while循环的外面
public List<CollectionBean> list() {String sql = "select * from collectiontbl";Connection conn = JDBC_Connection.getConnection();Statement stmt = null;ResultSet rs = null;List<CollectionBean> list = new ArrayList<CollectionBean>();try {stmt = conn.createStatement();rs = stmt.executeQuery(sql);CollectionBean bean = new CollectionBean();while (rs.next()) {//不能再while外面创建这个对象,这是一个非常有技术含量的问题 bean.setId(rs.getInt("id"));bean.setName(rs.getString("name"));bean.setName(rs.getString("url"));list.add(bean);}for(int i=0;i<list.size();i++){System.out.println(list.get(i).getId()+" "+list.get(i).getName());}return list;} catch (SQLException e) {e.printStackTrace();} finally {JDBC_Connection.free(rs, conn, stmt);}return null;}运行结果:1 www.dkfj.com2 www.dkfj.com3 www.dkfj.com4 www.dkfj.com5 www.dkfj.com6 www.dkfj.com
public List<CollectionBean> list() {String sql = "select * from collectiontbl";Connection conn = JDBC_Connection.getConnection();Statement stmt = null;ResultSet rs = null;List<CollectionBean> list = new ArrayList<CollectionBean>();try {stmt = conn.createStatement();rs = stmt.executeQuery(sql);while (rs.next()) {//不能再while外面创建这个对象,这是一个非常有技术含量的问题 CollectionBean bean = new CollectionBean();bean.setId(rs.getInt("id"));bean.setName(rs.getString("name"));bean.setName(rs.getString("url"));list.add(bean);}for(int i=0;i<list.size();i++){System.out.println(list.get(i).getId()+" "+list.get(i).getName());}return list;} catch (SQLException e) {e.printStackTrace();} finally {JDBC_Connection.free(rs, conn, stmt);}return null;}运行结果:1 www.baidu.com2 www.google.com3 www.google.com4 www.javaeye5 www.javaeye6 www.dkfj.com