private <T extends Object> T getResult(Class<?> className, String sql, String... params) { List<?> list = getResultList(className, sql, params); if (list != null && list.size() > 0) { return (T) list.get(0); } return null; } private <T extends List<?>> T getResultList(Class<?> className, String sql, String... params) { try { PreparedStatement st = conn.prepareStatement(sql); for (int i = 1; i <= params.length; i++) { st.setString(i, params[i - 1]); } List<Object> list = new ArrayList<>(); ResultSet result = st.executeQuery(); while (result.next()) { Object object = Class.forName(className.getName()) .newInstance(); Field[] fields = className.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; field.setAccessible(true); Class<?> typeClass = field.getType(); Constructor<?> con = typeClass.getConstructor(typeClass); Object value = con.newInstance(result.getString(field .getName())); field.set(object, value); } list.add(object); } return (T) list; } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } return null; }
注意:类的变量名必须与数据表中的字段名相同.
时间: 2024-10-14 23:48:37