Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

retrieve image


By the help of PreparedStatement we can retrieve and store the image in the database.

The getBlob() method of PreparedStatement is used to get Binary information, it returns the instance of Blob. After calling the getBytes() method on the blob object, we can get the array of binary information that can be written into the image file.

Signature of getBlob() method of PreparedStatement

  1. public Blob getBlob()throws SQLException

Signature of getBytes() method of Blob interface

  1. public  byte[] getBytes(long pos, int length)throws SQLException

We are assuming that image is stored in the imgtable.

  1. CREATE TABLE  “IMGTABLE”
  2.    (    “NAME” VARCHAR2(4000),
  3.     “PHOTO” BLOB
  4.    )
  5. /

Now let’s write the code to retrieve the image from the database and write it into the directory so that it can be displayed.

In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by the img tag.

  1. import java.sql.*;
  2. import java.io.*;
  3. public class RetrieveImage {
  4. public static void main(String[] args) {
  5. try{
  6. Class.forName(“oracle.jdbc.driver.OracleDriver”);
  7. Connection con=DriverManager.getConnection(
  8. “jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  9. PreparedStatement ps=con.prepareStatement(“select * from imgtable”);
  10. ResultSet rs=ps.executeQuery();
  11. if(rs.next()){//now on 1st row
  12. Blob b=rs.getBlob(2);//2 means 2nd column data
  13. byte barr[]=b.getBytes(1,(int)b.length());//1 means first image
  14. FileOutputStream fout=new FileOutputStream(“d:\\sonoo.jpg”);
  15. fout.write(barr);
  16. fout.close();
  17. }//end of if
  18. System.out.println(“ok”);
  19. con.close();
  20. }catch (Exception e) {e.printStackTrace();  }
  21. }
  22. }

Now if you see the d drive, sonoo.jpg image is created.

Comments

comments