Tuesday, 31 January 2017

Example to retrieve image from Oracle database:

Retrieving image from Oracle database

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.

public Blob getBlob()throws SQLException
Signature of getBytes() method of Blob interface

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

We are assuming that image is stored in the imgtable.

CREATE TABLE "IMGTABLE"
( "NAME" VARCHAR2(4000),
"PHOTO" 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.



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

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","system","oracle");
PreparedStatement ps=con.prepareStatement("select * from img");
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:\\bs.jpg");
fout.write(barr);
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}
}

AWS Migration Guide: Complete Cloud Migration Strategy for Businesses

AWS Internet of Things (IoT) Guide: Building Connected Device Solutions

AWS Internet of Things (IoT) Guide: Building Connected Device Solutions AWS Internet of Things (IoT) Guide: Building...