public List<Category> getCategoryList() throws SQLException {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {conn = DbUtil.getConnection();String sql = "select * from category";ps = conn.prepareStatement(sql);rs = ps.executeQuery(sql);List<Category> categoryList = new ArrayList<Category>();Category c = new Category();while (rs.next()) {c.setcId(rs.getInt("cId"));System.out.println("ci Dao===="+rs.getInt("cId"));c.setName(rs.getString("name"));c.setDescribes(rs.getString("describes"));c.setContentTime(rs.getString("contentTime"));categoryList.add(c);}System.out.println("categoryList.get(0).getCid()=="+categoryList.get(0).getcId());//輸出3System.out.println("categoryList.get(1).getCid()=="+categoryList.get(1).getcId());//輸出3 和上面的一樣 ???????return categoryList;} finally {DbUtil.close(rs, ps);}}
2 回答

慕婉清6462132
TA貢獻1804條經驗 獲得超2個贊
把Category c = new Category();寫到循環(huán)里面去就好了!
while (rs.next()) {
Category c = new Category();
c.setcId(rs.getInt("cId"));
System.out.println("ci Dao===="+rs.getInt("cId"));
c.setName(rs.getString("name"));
c.setDescribes(rs.getString("describes"));
c.setContentTime(rs.getString("contentTime"));
categoryList.add(c);
}

白板的微信
TA貢獻1883條經驗 獲得超3個贊
Category c = new Category();
這一句放到while循環(huán)里面去
否則只創(chuàng)建了一個對象
所有的操作都是對這一個對象進行的
所以只有最后一次循環(huán)生效了
必須在每次循環(huán)的時候new一個對象才可以
- 2 回答
- 0 關注
- 98 瀏覽
添加回答
舉報
0/150
提交
取消