话不多说,直接上代码。两代关于JDBC的代码,结果集到类对象的赋值。可直接使用于项目中。
作用:避免于大量的Setter/Getter的使用。
结果集到单一对象,一般用于查询单行记录时使用。
public static <T> T toOneRowObject(ResultSet rs, Class<T> beanClass) throws Exception {
T bean = null;
ResultSetMetaData metaData = rs.getMetaData();
if (rs.next()) {
bean = beanClass.newInstance();
int count = metaData.getColumnCount();
Object columnValue = "";
for (int idx = 1; idx <= count; idx++) {
columnValue = rs.getObject(idx);
switch(metaData.getColumnType(idx)){
case Types.TIMESTAMP:
case Types.TIME:
case Types.DATE:
columnValue = String.valueOf(rs.getObject(idx));
break;
case Types.BIGINT:
columnValue = rs.getInt(idx);
break;
}
PropertyUtils.setProperty(bean, metaData.getColumnLabel(idx), columnValue);
}
}
return bean;
}
结果集到多对象,使用于查询多行记录集。
public static <T> Vector<T> toMultiRowObject(ResultSet rs,Class<T> beanClass) throws Exception{
Vector<T> vc = new Vector<T>();
ResultSetMetaData metaData = rs.getMetaData();
int count = metaData.getColumnCount();
T bean = null;
Object columnValue = "";
try{
while(rs.next()){
bean = beanClass.newInstance();
for(int idx = 1;idx <= count;idx++){
columnValue = rs.getObject(idx);
switch(metaData.getColumnType(idx)){
case Types.TIMESTAMP:
case Types.TIME:
case Types.DATE:
columnValue = String.valueOf(rs.getObject(idx));
break;
case Types.BIGINT:
columnValue = rs.getInt(idx);
break;
}
PropertyUtils.setProperty(bean, metaData.getColumnLabel(idx), columnValue);
}
vc.add(bean);
}
}catch(Exception e){
throw new Exception("column value : " + columnValue, e);
}
return vc;
}
Demo清单:
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DBURL,DBUSER,DBPWD);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select * From t_user");
Vector vc = DBHelper.toMultiRowObject(rs, UserBean.class);
} catch (Exception e) {
log.error(sql.toString(), e);
e.printStackTrace();
} finally {
conn.close();
}