猿问

以下是部分代码,请高手帮忙看看问题出在哪里?

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());//输出3
System.out.println("categoryList.get(1).getCid()=="+categoryList.get(1).getcId());//输出3 和上面的一样 ???????

return categoryList;
} finally {
DbUtil.close(rs, ps);
}
}

SMILET
浏览 72回答 2
2回答

慕婉清6462132

把Category c = new Category();写到循环里面去就好了!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);}

白板的微信

Category c = new Category();这一句放到while循环里面去否则只创建了一个对象所有的操作都是对这一个对象进行的所以只有最后一次循环生效了必须在每次循环的时候new一个对象才可以
随时随地看视频慕课网APP
我要回答