方法:
public static List query(String sql, Class clazz,
Object[] parameters) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
ResultSetMetaData metaData = null;
List list = new ArrayList();
int index = 1;
try {
pstmt = conn.prepareStatement(sql);
if (parameters.length != 0) {
for (int i = 0; i < parameters.length; i++) {
// pstmt.setObject(第几个参数, 替换成什么);
pstmt.setObject(index, parameters[i]);
}
}
rs = pstmt.executeQuery(sql);
// 封装resultset
metaData = rs.getMetaData();
// 取出列的信息
int columnLength = metaData.getColumnCount();
// 获取列数
while (rs.next()) {
// 通过反射机制创建一个对象
T result = clazz.newInstance();
for (int i = 0; i < columnLength; i++) {
String metaDataKey = metaData.getColumnName(i + 1);
Object resultsetValue = rs.getObject(metaDataKey);
if (resultsetValue == null) {
resultsetValue = "";
}
Field field = clazz.getDeclaredField(metaDataKey);
field.setAccessible(true);
field.set(result, resultsetValue);
}
list.add(result);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
DBCloseUtils.closeCSR(conn, pstmt, rs);
}
return list;
}
测试:
sql = "select * from user_info where id > ? order by id asc";
list = databaseFactory.query(sql,User.class,new Object[]{2});
if (list != null) {
for (User user : list) {
System.out.println("username=" + user.username);
System.out.println("password=" + user.password);
}
System.out.println(sql);
System.out.println("inquiry4");
System.out.println("---------------------------");
}