Wednesday, 24 July 2013

How To insert and Retrieve image from DB #jdbc #java #MySQL

here is a few steps to insert and retrieve image files from DB.

1. Creating the Image column:




the image column will save a file , so it's recommend to make its  type blob.

Ex :
   CREATE  TABLE `mydb`.`tablename` (

  `id` INT NOT NULL AUTO_INCREMENT ,

  `image` BLOB NULL ,

  `image_name` VARCHAR(45) NULL ,

  PRIMARY KEY (`id`) );


2. Java code to insert Image :



  1.             File image = new File("c:/Me.jpg");
  2.             psmnt = connection.prepareStatement("insert into tablename (image , image_name) " + "values(? ,?)");

  3.             fis = new FileInputStream(image);
  4.             psmnt.setBinaryStream(1, (InputStream) fis, (int) (image.length()));
  5.             psmnt.setString(2,image.getName());
  6.            psmnt.executeUpdate();


3. Retrieve file from db :



  1.        rs = stmt.executeQuery("SELECT image , image_name FROM tablename ");
  2.        String filename = "";
  3.             while (rs.next()) {
  4.                 filename = rs.getString(2);
  5.                 Blob test = rs.getBlob("image");
  6.                 InputStream x = test.getBinaryStream();
  7.                 int size = x.available();
  8.                 OutputStream out = new FileOutputStream("c:/"+filename);
  9.                 byte b[] = new byte[size];
  10.                 x.read(b);
  11.                 out.write(b);
  12.             }

.
To handle retrieving Image in easy way . you can do below code in steps after line 5


  1.             byte[] image = rs.getBytes("image")
  2.             Image img = Toolkit.getDefaultToolkit().createImage(image);
  3.             ImageIcon icon = new ImageIcon(img);


Click here to download full Demo.

No comments:

Post a Comment