在我的postgres数据库表列中:
photograph bytea
我想从数据库中检索所有图像并将其保存到文件夹中。
到目前为止,我已经尝试了这个并且每次都变为null:
public class Test {
public static void main(String[] argv) throws SQLException, IOException {
System.out.println("-------- PostgreSQL "
+ "JDBC Connection Testing ------------");
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? "
+ "Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/a?currentSchema=a", "postgres"
+ "",
"123456");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//start
String query = "SELECT photograph FROM a.c limit 10";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
System.out.println(rs.getString(1));
// convert byte array back to BufferedImage
if(null == rs.getString(1)){
continue;
}
InputStream in = new ByteArrayInputStream(rs.getString(1).getBytes());
BufferedImage bImageFromConvert = ImageIO.read(in);
if(null == bImageFromConvert){
continue;
}
OutputStream out = new FileOutputStream("c:/"+"1"+".jpg");
ImageIO.write(bImageFromConvert, "jpg", out);
}
//end
} else {
System.out.println("Failed to make connection!");
}
}
}
调试后,我每次都得bImageFromConvert
为空。
On System out打印图像数据显示如下:
\xffd8ffe000104a46494600010101004800480000ffe1174a4578696600004d4d002a00000008000d01000004000000010000102001..
我将数据插入private Byte[] photograph;
如何解决这个问题??