日期:2014-05-16  浏览次数:20563 次

关于将数据库中的数据返回list的问题
  从数据库中返回list有两种方法:
一:先将数据库查询的结果集放一条一条的放入userbean
userbean的代码大概是:
package com.aixinshizhe;
public class UserBean{
private int userId;
private String username;
private String passwd;
private String email;
private int grade;
public void setUserId(int userId) {
this.userId = userId;
}

public void setUsername(String username) {
this.username = username;
}

public void setPasswd(String passwd) {
this.passwd = passwd;
}

public void setEmail(String email) {
this.email = email;
}

public void setGrade(int grade) {
this.grade = grade;
}

public int getUserId() {
return (this.userId);
}

public String getUsername() {
return (this.username);
}

public String getPasswd() {
return (this.passwd);
}

public String getEmail() {
return (this.email);
}

public int getGrade() {
return (this.grade);
}
}
userbean对应在数据库查询的结果集中的一条记录,
将结果集中数据一条一条的放入userbean,然后在将userbean放入list,代码为:
ArrayList al=new ArrayList();
while(rs.next()){
UserBean ub=new UserBean();
ub.setUserId(rs.getInt(1));
ub.setUsername(rs.getString(2));
ub.setPasswd(rs.getString(3));
ub.setEmail(rs.getString(4));
ub.setGrade(rs.getInt(5));
al.add(ub);
}

第二种方法:将数据放入到hash表中,在将hash表放入list,代码为:
List list = new ArrayList();
  ResultSetMetaData rsmd = rs.getMetaData();
       
            while ( rs.next() )
            {
                Map map = new HashMap();
               
                for ( int i = 1; i <= rsmd.getColumnCount(); i++ )
                {
                    map.put(rsmd.getColumnName(i), rs.getObject(i));
                }
               
                list.add(map);
            }