Saturday, 3 January 2015

How to Retrieve image in Oracle Database in Java


Using 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.

Syntax of getBlob() method of PreparedStatement

public Blob getBlob() throws SQLException

Syntax of getBytes() method of Blob interface

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

We are assuming that img is stored in the image table.

create table image( name varchar2(200), img blob);

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.

save as   RetrieveImage .java

import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[]args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from image");
ResultSet rs=ps.executeQuery();
if(rs.next()){   //now on 1st row
Blob b=rs.getBlob(2);  //2 means 2nd column data
byte barr[]=b.getBytes(1,(int)b.length());  //1 means first image
FileOutputStream fout=new FileOutputStream("d:\\rerose.jpg");
fout.write(barr);
fout.close();
}  
System.out.println("successfully image retrieved");
con.close();
}catch (Exception e) {
e.printStackTrace(); }
 }
}

Output: successfully image retrieved

No comments:

Post a Comment