//查询通用方法
//运用泛型集合和list集合,参数放class泛型,SQL语句,和SQL语句里的参数
public List getAll(Class clz, String sql, Object… params) {
ResultSet rs = getRs(sql, params);
List<T> datas = new ArrayList<>();
ResultSetMetaData rsmd = null;// 获取列的信息 (列名, 数据类型);
try {
rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
System.out.println("总共有:" + columnCount);
if (rs != null) {
//解析
while (rs.next()) {
// 使用反射
T t = clz.newInstance();
// Question question = new Question();
// 获取实体类里的所有的set方法
List setMethod = EntityUtil.getAllSetMethod(clz);// 包括了 get
for (int i = 0; i < setMethod.size(); i++) {
String methodName = setMethod.get(i).getName();
for (int j = 0; j < columnCount; j++) {
String cLable = rsmd.getColumnLabel(j + 1);// 从1开始
String cType = rsmd.getColumnTypeName(j + 1);// Varchar
if (methodName.toUpperCase().endsWith(cLable.toUpperCase())) {
// System.out.println(cLable + “:” + cType + “:” + setMethod.get(i).getName() + “:” + EntityUtil.getColumn(cLable, cType, rs));
setMethod.get(i).invoke(t, EntityUtil.getColumn(cLable, cType, rs));
break;
}
}
}
datas.add(t);
}
}
return datas;
} catch (SQLException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} finally {
closeAll(conn, ps, rs);
}
return null;
}
public ResultSet getRs(String sql, Object... params) {
conn = getConnection();
ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(sql);
// 添加参数
if (params != null) {
//解析SQL语句里的参数
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rs = ps.executeQuery();
return rs;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}