Saturday, 3 January 2015

How to Store image in Oracle Database in Java


You can store images in the database in java by the help of  PreparedStatement  interface. The setBinaryStream() method of PreparedStatement is  used to set Binary information into the parameterIndex.

Syntax of setBinaryStream() method is given below:

>1. public void setBinaryStream(int paramIndex,InputStream stream) throws SQLException
>2. public void setBinaryStream(int paramIndex,InputStream stream,long length)  throws SQLException

For storing image into the oracle database, BLOB (Binary Large Object) datatype is used while creating the table.

For example:

create table image ( name varchar2(300),  img blob)

Below  is the  code to store the image in the database.Here we are using d:\\rose.jpg for the location of image. You can change it according to the image location.

save as  InsertImage.java

 import java.sql.*;
 import java.io.*;
 public class InsertImage {
 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("insert into image values(?,?)");
 ps.setString(12,"flower");
 FileInputStream fin=new FileInputStream("d:\\rose.jpg");
 ps.setBinaryStream(2, fin, fin.available());
 int i=ps.executeUpdate();
 System.out.println(i+" record affected");
 con.close();
 }catch (Exception e) {
e.printStackTrace(); }
   }
 }

 Output: 1 record affected


If you see the table, 1 record is stored in the database but image will not be shown. To do so, you need to retrieve the image from the database which we are covering in the next post.

Next Post:  How to Retrieving image from Oracle Database
  

No comments:

Post a Comment