日期:2014-05-20  浏览次数:20862 次

如何将ResultSet返回成ARRAYLIST哦
如何让查询出来的数据集返回成ARRAYLIST哦各位,帮帮我

------解决方案--------------------
ArrayList smallList=new ArrayList();
ArrayList biggerList=new ArrayList();
while(rs.next){
smallList.clear();
smallList.add(rs.getString( " "))
...
...
Object[] obj=new Object[smallList.size()];
smallList.array(obj);
biggerList.add(obj);

}
return biggerList;



------解决方案--------------------
public static Collection getXXXX()
throws ServiceException {
Statement sqlStrStmt = null;
ResultSet rs = null;
Connection con = xxx.getConnection();
Collection lst = new ArrayList();
try {
String strSql = "select * from table ";
sqlStrStmt = con.createStatement();
rs = sqlStrStmt.executeQuery(strSql);
while (rs.next()) {
lst.add(new Integer(rs.getInt( "XXX ")));
}
rs.getStatement().close();
} catch (SQLException e) {
...
} finally {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
...
}
}
}
return lst;
}
------解决方案--------------------
你可以定义一个bean,bean的属性就是你resultset中的各个字段,然后循环rs,读取数据,每一行数据生成一个bean对象,放入ArrayList不就行了。

当然上面的工作已经有人做了,就是apache下的commons/beanutils子项目中有一个RowSetDynaClass类具体的使用方法:
Connection conn = ...; // Acquire connection from pool
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery( "SELECT id,name from users ");
RowSetDynaClass rsdc = new RowSetDynaClass(rs);
rs.close();
stmt.close();
...; // Return connection to pool
List rows = rsdc.getRows();
...; // Process the rows as desired
for(java.util.Iterator i=rows.iterator();i.hasNext();)
{
org.apache.commons.beanutils.DynaBean bean=(org.apache.commons.beanutils.DynaBean)i.next();
System.out.println( "id: "+bean.get( "id ")+ ", name: "+bean.get( "name "));
}
------解决方案--------------------

public final Collection <SpInfoForm> listAllCodeTest() {
ArrayList <SpInfoForm> list = new ArrayList();
String sql = "select spName,spID from spinfo ";
try {
Connection conn = dbmAuth.getConnection();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
System.out.println(sql);
while (rs.next()) {
SpInfoForm sf = new SpInfoForm();
sf.setSpName(rs.getString(1));
sf.setSpID(rs.getString(2));

System.out.println(rs.getString(1));
list.add(sf);
}
dbmAuth.closeConn(conn, stmt, rs);
} catch (SQLException e) {
e.printStackTrace();
}

return list;
}
------解决方案--------------------
通用方法接收一个sql语句 返回一个装有LinkedHashMap的ArrayList集合 其中LinkedHashMap的KEY为数据库字段名 VALUE为该字段的值

public static ArrayList delRes(String sql) {
ArrayList <LinkedHashMap> list = new ArrayList <LinkedHashMap> ();
Connection conn = null;
PreparedStatement stmt = null;
ResultSetMetaData metaData=null;
try {
conn = ConDB.getCon();
stmt = (PreparedStatement) conn.prepareStatement(sql);
ResultSet result = stmt.executeQuery();
metaData=result.getMetaData();