0

I want to display / print the Blob image from database. with the following code it only shows this :

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

The correct data for name and phone works but the blob don't show a image. What am I doing wrong? Any help?

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) {
  }
}
John Doe
  • 47
  • 1
  • 7

1 Answers1

2

You cab't print a Blob object to the stdout. Here my code shows how to create an stream out of it and save it to a file. You can use the InputStream(is) to do anything.

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();
Eranda
  • 1,439
  • 1
  • 17
  • 30
  • Why do you have " /user/eranda/temp/MyImage.png "? – John Doe May 20 '15 at 18:07
  • I am saving the blob to a file which named as MyImage.png. – Eranda May 20 '15 at 18:08
  • I just changed it to my own location, but when i print the image it shows the url "Pic: /Users/John/Downloads/image.jpg What variable is used to get the blob? Is it image? – John Doe May 20 '15 at 18:11
  • resultSet is what I retrieve from the database and I am getting it as an InputStream and use it to save the blob as MyImage. In your case it is rs. – Eranda May 20 '15 at 18:26
  • I change it to rs. but I still get the path to the image as output not the image. What variable do I need to print to show the image? – John Doe May 20 '15 at 18:34