John Doe
John Doe

Reputation: 47

Display Blob from database with java

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) {
  }
}

Upvotes: 0

Views: 5407

Answers (1)

Eranda
Eranda

Reputation: 1467

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

Upvotes: 2

Related Questions