使用java显示数据库中的Blob

时间:2015-05-20 17:42:01

标签: java database blob

我想从数据库中显示/打印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) {
  }
}

1 个答案:

答案 0 :(得分:1)

您可以将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();