- Java code
public List<User> list(){ List<User> users=new ArrayList<User>(); Connection conn=this.getConnection(); ResultSet rs=null; String sql="select id,username,password,age,address from user"; PreparedStatement ps=this.prepare(conn, sql); User user=new User(); try{ rs=ps.executeQuery(); while(rs.next()){ user.setId(rs.getInt(1)); user.setUsername(rs.getString(2)); user.setPassword(rs.getString(3)); user.setAddress(rs.getString(4)); users.add(user); } }catch(Exception e){ e.printStackTrace(); } return users; }
- Java code
public static void main(String[] args) { Main main=new Main(); List<User> allUser=main.list(); Iterator<User> iterator=allUser.iterator(); while(iterator.hasNext()){ User user=iterator.next(); System.out.println(user.getUsername()); } }
为什么输出的总是最后一条数据啊~ 希望各位给的详细点 谢谢了
------解决方案--------------------
因为你只有一个User user = new User();
所以从始至终你都只创建了一个user对象,而代码
- Java code
while(rs.next()){ user.setId(rs.getInt(1)); user.setUsername(rs.getString(2)); user.setPassword(rs.getString(3)); user.setAddress(rs.getString(4)); users.add(user); }