gpt4 book ai didi

java - 用java显示数据库中的Blob

转载 作者:行者123 更新时间:2023-12-01 11:31:22 24 4
gpt4 key购买 nike

我想显示/打印数据库中的 Blob 图像。使用以下代码,它仅显示此:

Pic: com.mysql.jdbc.Blob@1e1a68bc
Name:Test
Phone:1234

姓名和电话的正确数据有效,但 Blob 不显示图像。我究竟做错了什么?有什么帮助吗?

try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/Test", "root", "");
stmt = conn.createStatement();

String query = "SELECT * FROM Person WHERE email ='"+emailLogin+"'";
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String name = rs.getString("name");
String telephone = rs.getString("telephone");
Blob pic = rs.getBlob("foto");

out.print("Picture: "+pic + "<br>");
out.print("Name: "+name + "<br>");
out.print("Phone: "+telephone + "<br>");

}
} catch (SQLException e) {
out.println("An error occured while retrieving " + "all results: "
+ e.toString());
} catch (ClassNotFoundException e) {
throw (new ServletException(e.toString()));
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
}
}

最佳答案

您无法将 Blob 对象打印到标准输出。这里我的代码展示了如何从中创建流并将其保存到文件中。您可以使用InputStream(is) 执行任何操作。

File image = new File("/user/eranda/temp/MyImage.png");
FileOutputStream fos = new FileOutputStream(image);
byte[] buffer = new byte[1];
InputStream is = resultSet.getBinaryStream("foto");
while (is.read(buffer) > 0) {
fos.write(buffer);
}
fos.close();

关于java - 用java显示数据库中的Blob,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30356762/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com