How to Read BLOBs Data from Database/Resultset in Java?

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

Below java code shows how to read BLOBs column database from database-

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

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.*;

/**
 * Created by http://kodehelp.com
 * Date: 5/9/11
 */
public class ReadBLOBData {
     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;
        try{
          Class.forName(driver); // load Oracle driver
          conn = DriverManager.getConnection(url, USERNAME, PASSWORD);
          String sql = "SELECT name, description, image FROM pictures ";
          PreparedStatement stmt = conn.prepareStatement(sql);
          ResultSet resultSet = stmt.executeQuery();
          while (resultSet.next()) {
                String name = resultSet.getString(1);
                System.out.println("Name        = " + name);
                String description = resultSet.getString(2);
                System.out.println("Description = " + description);

                File image = new File("D:\\java.gif");
                FileOutputStream fos = new FileOutputStream(image);
                byte[] buffer = new byte[256];

                //
                // Get the binary stream of our BLOB data
                //
                InputStream is = resultSet.getBinaryStream(3);
                while (is.read(buffer) > 0) {
                    fos.write(buffer);
                }

                fos.close();
            }
        }catch (ClassNotFoundException cnfEx){
            throw cnfEx;
        }catch (SQLException sqlEx){
            throw sqlEx;
        }catch(FileNotFoundException fnfEx){
            throw fnfEx;
        }catch(Exception ex){
            throw ex;
        }finally{
            if(conn!=null){
                conn.close();
            }
        }
    }
}