51,402
社区成员




String sql = "SELECT * FROM resource WHERE id = ?";
String[] path = new String[1];
path[0] = "F:\\program design\\JavaWeb\\web\\resource\\2.png";
ArrayList<Datas> arrayList = JDBC.searchBolb(connection, Datas.class, sql, path, 1);
PrintWriter writer = response.getWriter();
for (Datas d : arrayList) {
writer.println(d);
}
public static <T> ArrayList<T> searchBolb(Connection connection, Class<T> clazz, String sql, String[] resourcePath, Object... args) {
//数据库表中最后一个字段为Blob类型
//输出类中封装Blob资源输出地址
PreparedStatement ps = null;
ResultSet result = null;
ResultSetMetaData rsmd = null;
InputStream is = null;
FileOutputStream fos = null;
int resourcePathNumber = 0;
ArrayList<T> collection = new ArrayList<T>();
try {
ps = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
result = ps.executeQuery();
rsmd = result.getMetaData();
//无法调试这个while循环
while (result.next()) {
int columnCount = rsmd.getColumnCount();
T t = clazz.getDeclaredConstructor().newInstance();
for (int i = 0; i < columnCount - 1; i++) {
Object columnValue = result.getObject(i + 1);
String columnLabel = rsmd.getColumnLabel(i + 1);
Field field = clazz.getDeclaredField(columnLabel);
field.setAccessible(true);
field.set(t, columnValue);
}
Blob blob = result.getBlob(columnCount);
String blobLabel = rsmd.getColumnLabel(columnCount);
Field field = clazz.getDeclaredField(blobLabel);
field.setAccessible(true);
field.set(t, resourcePath);
is = blob.getBinaryStream();
fos = new FileOutputStream(resourcePath[resourcePathNumber++]);
byte[] buffer = new byte[1024];
int len;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
collection.add(t);
}
} catch (SQLException | IOException | NoSuchFieldException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
e.printStackTrace();
} finally {
try {
ps.close();
is.close();
fos.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
if (collection == null) {
System.out.println("Failed to search");
}
return collection;
}
}