January 1, 2012

JDBC Code to read BLOB data type from database table

0) Complete the example to store an image (BLOB data) to a table at the link here

1) Create a Java class - JdbcBlobReader.java - in the src folder of the Java Project / application

package info.icontraining.jdbc;

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

public class JdbcBlobReader {
 
   public static void main(String[] args) throws Exception, IOException, SQLException {
   
      Class.forName("oracle.jdbc.OracleDriver");
      Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","system");

      PreparedStatement pstmt = conn.prepareStatement("Select name, image from MyImages");
      ResultSet rs = pstmt.executeQuery();
      
      while (rs.next()) {
         String name = rs.getString(1);
         String description = rs.getString(2);
         File image = new File("src/icon-training-downloaded.jpg");
         FileOutputStream fos = new FileOutputStream(image);

         byte[] buffer = new byte[1];
         InputStream is = rs.getBinaryStream(2);

         while (is.read(buffer) > 0) {
            fos.write(buffer);
         }

         fos.close();
      }

      conn.close();    
   }
}

2) Run the code as a standalone Java Application

No comments:

Post a Comment