jdbc利用反射获得值时,Java.util.Date无法转换为String . 感谢帮忙!!
//功能为单独表的查询。//报错为:(查询其余正确,在查询Date时报下面错误)
public Stuinjava.lang.IllegalArgumentException: [b]Can not set java.util.Date field jdbc.bean.Stuinfo.birth to java.lang.String fo queryForStuinfo(String sql,Object...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1.获取数据库的连接
conn = JDBCUtils.getConnection();
//2.预编译sql语句并返回preparedStatement的实例
ps = conn.prepareStatement(sql);
for (int i = 0; i <args.length; i++) {
ps.setObject(i+1,args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaDa();
ResultSetMetaData rsmd = rs.getMetaData();
//通过ResultSetMeData获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if(rs.next()){
Stuinfo stuinfo = new Stuinfo();
//处理结果集一行数据中的每一个列
for (int i = 0; i <columnCount ; i++) {
//获取列值
Object columValue = rs.getObject(i + 1);
//获取每个列的列名
String columnName = rsmd.getColumnName(i+1);
//给stuinfo对象指定的columnName属性:赋值为columnValue通过反射
Field declaredField = Stuinfo.class.getDeclaredField(columnName);
declaredField.setAccessible(true);
declaredField.set(stuinfo,columValue);
}
return stuinfo;
}
} catch (Exception e){
e.printStackTrace();
} finally {
JDBCUtils.closeResource(conn,ps,rs);
}
return null;
}