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) {
  }
}
1
  • Perhaps this answer could help (even if it's for Oracle). Commented May 20, 2015 at 18:38

1 Answer 1

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();
Sign up to request clarification or add additional context in comments.

5 Comments

Why do you have " /user/eranda/temp/MyImage.png "?
I am saving the blob to a file which named as MyImage.png.
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?
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.
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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.