星期三, 五月 16, 2007

用List传递Resultset对象 得到的不同类型对象

public static ArrayList<LinkedHashMap> delRes(String sql) {
    ArrayList<LinkedHashMap> list = new ArrayList<LinkedHashMap>();

    Connection con = null;
    PreparedStatement stmt = null;
    ResultSetMetaData metaData=null;
    try {
        con = ConDB.getCon();
        stmt = (PreparedStatement) con.prepareStatement(sql);
        ResultSet result = stmt.executeQuery();
        metaData=result.getMetaData();
        while (result.next()) {
            LinkedHashMap v = new LinkedHashMap();
            for (int i = 1; i <= metaData.getColumnCount (); i++)
                v.put(metaData.getColumnLabel(i),result.getObject(i));

            list.add(v);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    } finally {
        try {
            if (stmt != null) {
            stmt.close();
            }
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return list;
}
 
 
待确认方法,利用反射
ResultSetMetaData rsm=rs.getMetaData();
Object domain=null;
while(rs.next()){
    domain=Class.forName("Domain").newInstance();
    for(int i=1;i<=rsm.getColumnCount();i++){
        String recordValue= rs.getString(rsm.getColumnName(i));
        Method m=domain.getClass().getMethod("set"+rsm.getColumnName(i),new Class[]{recordValue.getClass()});
        m.invoke(domain,new Object[]{recordValue});
   }
   list.add(domain);
}
 

没有评论: