0

I have the following structure. I am joining some tables together to get a result from my SQL database. I have a column that actually stores an BLOB image in it. I would like to know how can I retrieve this information in a variable that can then be used to load this image in a Graphical User Interface such as swing window.

Here is my code on how I am reading other - String - fields of the database.

ResultSet result = statement.executeQuery(SQLQuery);
ResultSetMetaData metaData = rs.getMetaData();

while (result.next())
{

  for (int i = 1; i <= columnsNumber; i++)
  {
         String AttributeName = metaData.getColumnName(i);
         String AttributeValue = result.getString(i);

         if(AttributeName == "UserName")
         {
             String userName = AttributeValue;
         }
         if(AttributeName == "UserImage")
         {
             //code here to get the BLOB user Image.?
         }
   }
}

And lastly an idea of how can, with a given picture (from the filesystem) to store this image as BOLB in the database?

Cheers.

I read about this one but I think this implementation can't help me.

Community
  • 1
  • 1
Phrixus
  • 1,209
  • 2
  • 19
  • 36

1 Answers1

0

There you go, just integrate both your and my loop:

 while (resultSet.next()) {
  // String name = resultSet.getString(1);
  // String description = resultSet.getString(2);
  File image = new File("your path");
  FileOutputStream fos = new FileOutputStream(image);
  byte[] buffer = new byte[1];

  InputStream is = resultSet.getBinaryStream(3);
  while (is.read(buffer) > 0) {
    fos.write(buffer);
  }
  fos.close();
}

Of course remember to properly modify path and InputStream is = resultSet.getBinaryStream(3); lines. Good luck!

  • Thanks! I will give it a try. Is there ant chance to use the image to show it in the GUI without actually writing the picture to the filesystem ? – Phrixus Feb 27 '15 at 16:39
  • Yes, use ByteArrayOutputStream instead of FileOutputStream. Shall I update my answer or will you manage? –  Feb 27 '15 at 16:40
  • And this ByteArrayOutputStream will be used to write it to an ImageIcon object or how? – Phrixus Feb 27 '15 at 16:41
  • You can just canstruct it with this stream: new ImageIcon(bos.toByteArray()); –  Feb 27 '15 at 16:44
  • Sure. If you have any more questions feel free to ask. –  Feb 27 '15 at 16:45
  • If the answer helped you - please mark it as per guidelines. –  Mar 03 '15 at 14:21