Share two method for JDBC's ResultSet convert into different data format list, one is for json, other is object instance.
/**
* Convert ResultSet to List, data format for JSON
* @param rs
* @return
* data format:[{CORPNO=TCS0232,TAXNO=Tax001},{CORPNO=TCS0232,TAXNO=Tax001}]
* @throws SQLException
*/
@SuppressWarnings("unchecked")
private static List convertList(ResultSet rs) throws SQLException {
//Container
List list = new ArrayList();
//Get the element of resultSet
ResultSetMetaData md = rs.getMetaData();
//Map rowData;
int columnCount = md.getColumnCount();
//Use Map
while (rs.next()) {
Map rowData = new HashMap();
//Fill up
for (int i = 1; i <= columnCount; i++) {
rowData.put(md.getColumnName(i), rs.getObject(i));
}
//Fill up
list.add(rowData);
}
//back
return list;
}
/**
* Convert ResultSet to List, data format for Object
*
* @param rs
* @param clazz
* @return
* A list of data object( For the some Class) instance.
* @throws Exception
*/
@SuppressWarnings("unchecked")
public static List populate(ResultSet rs,Class clazz) throws Exception{
//Get the element of resultSet
ResultSetMetaData metaData = rs.getMetaData();
//Get count
int colCount = metaData.getColumnCount();
//Container
List ret = new ArrayList();
//Get Object attributes
Field[] fields = clazz.getDeclaredFields();
//Construct it
while(rs.next()){
Object newInstance = clazz.newInstance();
for(int i=1;i<=colCount;i++){
try{
Object value = rs.getObject(i);
for(int j=0;j<fields.length;j++){
Field f = fields[j];
if(f.getName().equalsIgnoreCase(metaData.getColumnName(i).replaceAll("_",""))){
BeanUtils.copyProperty(newInstance,f.getName(),value);
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
//Fill into
ret.add(newInstance);
}
//Back
return ret;
}
本文出自 “专注J2EE系列规范下的..” 博客,请务必保留此出处http://danni505.blog.51cto.com/15547/265906