«Back to Home

Core Java

Topics

How To Store Image In Database

Store image in Database
 
In JDBC, PreparedStatement setBinaryStream() method is used to set the binary information into the the parameterIndex.
 
We can store the images in the database in Java by the use of PreparedStatement interface.
 
Syntax of setBinaryStream method

public void setBinaryStream(int paramIndex,InputStream stream) throws SQLException
 
public void setBinaryStream(int paramIndex,InputStream stream,long length) throws SQLException
 
BLOB (Binary Large Object) data type is used in the table to store an image into the database.
 
Example
 
CREATE TABLE "IMAGETABLE"
( "NAME" VARCHAR2(2000),
"PHOTO" BLOB
)
 
Let’s see an example, given below.
 
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("insert into STUDENT.IMAGETABLE values(?,?)");  
  11.         ps.setString(1"flower");  
  12.         FileInputStream fin = new FileInputStream("B:\\photos\\2014-11-02\\11.jpg");  
  13.         ps.setBinaryStream(2, fin, fin.available());  
  14.         int i = ps.executeUpdate();  
  15.         System.out.println(i + " records affected");  
  16.         conn.close();  
  17.     }  
  18. }  
31

Output

32

In the example shown above, we are using “B:\\photos\\2014-11-02\\11.jpg” for the location of an image. We can change it according to the image location.
 
Summary

Thus, we learned that we can store images in the database in Java by the use of PreparedStatement interface and also learn how to store image in Java database.