«Back to Home

Core Java

Topics

How To Retrieve Image From Database

Retrieve image from Database
 
We can retrieve and store the image in the database with the use of PreparedStatement.
 
In JDBC, the PreparedStatement getBlob() method is used to get the binary information and it returns the object of Blob. We can get the array of the binary information, which can be written into the image file after calling thegetBytes() method on the blob object.
 
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
 
Example

CREATE TABLE "IMAGETABLE"
( "NAME" VARCHAR2(2000),
"PHOTO" BLOB
)
 
Let’s see an example.
 
Code
  1. import java.sql.*;  
  2. import java.io.*;  
  3. public class StudentDatabase2 {  
  4.     public static void main(String args[]) throws Exception {  
  5.         Class.forName("org.apache.derby.jdbc.ClientDriver");  
  6.         String url = "jdbc:derby://localhost:1527/Student";  
  7.         String username = "Student";  
  8.         String password = "student";  
  9.         Connection conn = DriverManager.getConnection(url, username, password);  
  10.         PreparedStatement ps = conn.prepareStatement("select * from STUDENT.IMAGETABLE");  
  11.         ResultSet rs = ps.executeQuery();  
  12.         if (rs.next()) {  
  13.             Blob b = rs.getBlob(2);  
  14.             byte barr[] = b.getBytes(1, (int) b.length());  
  15.             FileOutputStream fout = new FileOutputStream("B:\\photos\\2014-11-02\\11.jpg");  
  16.             fout.write(barr);  
  17.             fout.close();  
  18.         }  
  19.         System.out.println("Ok");  
  20.         conn.close();  
  21.     }  
  22. }  
33

Output

34

Now, if we see the B drive, image is created.
 
Summary

Thus, we learnt, we can retrieve and store the image in the database with the use of PreparedStatement and also learnt, how to retrieve an image from the database in Java.