簡體   English   中英

使用Java從數據庫顯示Blob

[英]Display Blob from database with java

我想顯示/打印數據庫中的Blob圖像。 使用以下代碼,它僅顯示以下內容:

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

名稱和電話的正確數據有效,但斑點不顯示圖像。 我究竟做錯了什么? 有什么幫助嗎?

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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM