How to Store BLOBs Data into Database in Java?

DeeKay May 9, 2011 at 6:54 pm · java.sql

Below Java code shows how to store BLOB object into database –

Database BLOBs (Binary Large Objects) can be used to stored any data, it could be image, audio or video file for instance. This example shows you how we use JDBC library to store image in our database. To send the binary information to the database we can call the PreparedStatement.setBinaryStream() method and pass the appropriate input stream and it size.

/****************************************************************************************
 * Created on 05-2011 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javasql;

import java.io.*;
import java.sql.*;

/**
 * Created by http://kodehelp.com
 * Date: 5/9/11
 */
public class StoreBLOBData {
    public static void main(String[] args) throws Exception, ClassNotFoundException, FileNotFoundException {
        final String driver = "oracle.jdbc.driver.OracleDriver";
        final String url = "jdbc:oracle:thin:@HOST:PORT:SID";
        final String USERNAME = "USERNAME";
        final String PASSWORD = "PASSWORD";
        Connection conn = null;
        FileInputStream fis = null;
        try{
          Class.forName(driver); // load Oracle driver
          conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
          String sql = "INSERT INTO pictures (name, description, image) VALUES (?, ?, ?)";
          PreparedStatement stmt = conn.prepareStatement(sql);
          stmt.setString(1, "java.gif");
          stmt.setString(2, "Java Official Logo");

          File image = new File("D:\\Projects\\kodehelp\\images\\java.gif");
          fis = new FileInputStream(image);
          stmt.setBinaryStream(3, fis, (int) image.length());
          stmt.execute();
        }catch (ClassNotFoundException cnfEx){
            throw cnfEx;
        }catch (SQLException sqlEx){
            throw sqlEx;
        }catch(FileNotFoundException fnfEx){
            throw fnfEx;
        }catch(Exception ex){
            throw ex;
        }finally{
            if (fis != null) {
                fis.close();
            }
            if(conn!=null){
                conn.close();
            }
        }
    }
}