【问题标题】:Display Blob from database with java使用 java 从数据库中显示 Blob
【发布时间】:2015-08-02 02:51:34
【问题描述】:

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

【问题讨论】:

  • 也许this answer 会有所帮助(即使是针对 Oracle 的)。

标签: java database blob


【解决方案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();

【讨论】:

  • 为什么会有“ /user/eranda/temp/MyImage.png ”?
  • 我将 blob 保存到一个名为 MyImage.png 的文件中。
  • 我只是将其更改为我自己的位置,但是当我打印图像时它显示 url “Pic: /Users/John/Downloads/image.jpg 什么变量用于获取 blob?是它的图像?
  • resultSet 是我从数据库中检索的内容,我将其作为 InputStream 获取并使用它将 blob 保存为 MyImage。在你的情况下,它是 rs。
  • 我把它改成rs。但我仍然得到图像的路径作为输出而不是图像。我需要打印什么变量来显示图像?
猜你喜欢
  • 2014-02-21
  • 1970-01-01
  • 2012-01-09
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 2012-03-09
  • 2018-03-18
  • 2015-04-06
相关资源
最近更新 更多