Java JDBC利用反射技术将查询结果封装为对象
1、JDBC将返回结果集封装成对象demo
class JdbcDemo { /** * 获取数据库列名 * @param rs * @return */ private static String[] getColNames(ResultSet rs) throws SQLException { ResultSetMetaData rsmd = rs.getMetaData(); //获取查询的列数 int count = rsmd.getColumnCount(); String[] colNames = new String[count]; for(int i = 1; i <= count; i ++) { //获取列名 colNames[i - 1] = rsmd.getColumnLabel(i); } return colNames; } /** * 将JDBC查询返回的结果集,利用反射封装成对象 * @param sql * @param clazz * @return */ private static Object getObject(String sql, Class clazz) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = JdbcUtils.getConnection(); ps = conn.prepareStatement(sql); rs = ps.executeQuery(); String[] colNames = getColNames(rs); Object object = null; Method[] ms = clazz.getMethods(); if(rs.next()) { object = clazz.newInstance(); for(int i = 0; i < colNames.length; i ++) { String colName = colNames[i]; String methodName = "set" + colName; //稳妥一点。在对象查询下是否有此方法在调用方法 for(Method md : ms) { if(methodName.equals(md.getName())) { md.invoke(object, rs.getObject(colName)); break; } } } } return object; } finally { //释放连接 JdbcUtils.free(rs, ps, conn); } } }
感谢您的阅读,您的支持是我写博客动力。