Dev Language/JAVA

ResultSet을 컬렉션으로 반환

타카스 류지 2016. 6. 16. 09:42

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p></p>
 * @author Lee Jeong Hak(pluggers@naver.com)
 * @version $Revision: 1.2 $ $Date: 2004/05/06 01:27:53 $

 *  ResultSet을 컬렛션으로 반환
 */
public class RsToCollection {

    private int rsCount;
    private List rsList = new ArrayList();
    private ResultSet rs = null;

    /**
     * 
     */
    public RsToCollection(ResultSet rs) {
        this.rs = rs;
    }

    /**
     * @param rs
     * @return
     * @throws SQLException
     */
    private Object doCreateRow(ResultSet rs) throws SQLException {
        Map result = new HashMap();
        ResultSetMetaData rsmd = rs.getMetaData();
        int count = rsmd.getColumnCount();
        for (int i = 1; i <= count; i++) {
            String label = rsmd.getColumnLabel(i);
            Object value = rs.getObject(i);
            if (label != null && value != null) {
                result.put(label.toUpperCase(), value);
            }
        }
        return result;
    }
    /**
     * @param rs
     * @return
     */
    public List getRsList() {
        try {
            while (rs.next()) {
                Object obj = doCreateRow(rs);
                if (obj instanceof Object[]) {
                    for (int i = 0; i < ((Object[]) obj).length; i++) {
                        rsList.add(((Object[]) obj)[i]);
                    }
                } else {
                    rsList.add(obj);
                }
            }
            rsCount = rsList.size();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rsList;
    }
    /**
     * @return
     */
    public Map getMapList(ResultSet rs) {
        getRsList();
        return (Map) rsList.get(0);
    }
    /**
     * @return
     */
    public int getRsCount() {
        return rsCount;
    }

    /**
     * @param i
     */
    public void setRsCount(int i) {
        rsCount = i;
    }

}