* 把得到的一列数据存入到一个对象中
* @param rs
* @return
* @throws InstantiationException
* @throws IllegalAccessException
* @throws SQLException
* @throws NoSuchMethodException
* @throws SecurityException
* @throws IllegalArgumentException
* @throws InvocationTargetException
*/
@SuppressWarnings("unchecked")
private E oneRowToObject(ResultSet rs) throws InstantiationException, IllegalAccessException, SQLException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
E obj;
obj=(E) cls.newInstance();
//获取结果集元数据(获取此 ResultSet 对象的列的编号、类型和属性。)
ResultSetMetaData rd=rs.getMetaData();
for (int i = 0; i < rd.getColumnCount(); i++) {
//获取列名
String columnName=rd.getColumnLabel(i+1);
//组合方法名
String methodName="set"+columnName.substring(0, 1).toUpperCase()+columnName.substring(1);
//获取列类型
int columnType=rd.getColumnType(i+1);
Method method=null;
switch(columnType) {
case java.sql.Types.VARCHAR:
case java.sql.Types.CHAR:
method=cls.getMethod(methodName, String.class);
if(method!=null) {
method.invoke(obj, rs.getString(columnName));
}
break;
case java.sql.Types.INTEGER:
case java.sql.Types.SMALLINT:
method=cls.getMethod(methodName, int.class);
if(method!=null) {
method.invoke(obj, rs.getInt(columnName));
}
break;
case java.sql.Types.BIGINT:
method=cls.getMethod(methodName, long.class);
if(method!=null) {
method.invoke(obj, rs.getLong(columnName));
}
break;
case java.sql.Types.DATE:
case java.sql.Types.TIMESTAMP:
try {
method=cls.getMethod(methodName, Date.class);
if(method!=null) {
method.invoke(obj, rs.getTimestamp(columnName));
}
} catch(Exception e) {
method=cls.getMethod(methodName, String.class);
if(method!=null) {
method.invoke(obj, rs.getString(columnName));
}
}
break;
case java.sql.Types.DECIMAL:
method=cls.getMethod(methodName, BigDecimal.class);
if(method!=null) {
method.invoke(obj, rs.getBigDecimal(columnName));
}
break;
case java.sql.Types.DOUBLE:
case java.sql.Types.NUMERIC:
method=cls.getMethod(methodName, double.class);
if(method!=null) {
method.invoke(obj, rs.getDouble(columnName));
}
break;
case java.sql.Types.BIT:
method=cls.getMethod(methodName, boolean.class);
if(method!=null) {
method.invoke(obj, rs.getBoolean(columnName));
}
break;
default:
break;
}
}
return obj;
}
|