从MySQL读取数据,以List方式传出

来源:百度知道 编辑:UC知道 时间:2024/09/28 08:00:56
代码如下:
public List selectDb() {
List list=new ArrayList();
InfoForm info=new InfoForm();
Statement sm=null;
ResultSet rs=null;
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost/newdb","root","rxsoft");
sm=con.createStatement();
rs=sm.executeQuery("select * from user");
while(rs.next()){
info.setUserID(rs.getInt("userid"));
info.setUserName(rs.getString("username")); info.setPassWord(rs.getString("password"));
list.add(info);
}
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException ex){
ex.printStackTrace();
}finally{
try{
if (rs!=null){
rs.close();
rs=null;
}
if(sm!=null){
sm.close();
sm=null;
}

每次产生一个info对象,不使用一个info对象。
while(rs.next()){
InfoForm info=new InfoForm();
info.setUserID(rs.getInt("userid"));
info.setUserName(rs.getString("username")); info.setPassWord(rs.getString("password"));
list.add(info);
}

上面回答正确 因为你没有把 new 对象放在循环内 所以总是原来的对象往LIST里放 当然覆盖了.