Read image(BLOB) data from database in Java

Description

The following code shows how to read image(BLOB) data from database.

Example


/*from w  w  w.jav a  2  s. c  o  m*/
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class Main {
  static String url = "jdbc:oracle:thin:@localhost:1521:javaDemo";
  static String username = "username";
  static String password = "welcome";
  public static void main(String[] args) throws Exception {
    Class.forName("oracle.jdbc.driver.OracleDriver");
    Connection 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);
      String description = resultSet.getString(2);
      File image = new File("D:\\java.gif");
      FileOutputStream fos = new FileOutputStream(image);

      byte[] buffer = new byte[1];
      InputStream is = resultSet.getBinaryStream(3);
      while (is.read(buffer) > 0) {
        fos.write(buffer);
      }
      fos.close();
    }
    conn.close();
  }
}




















Home »
  Java Tutorial »
    JDBC »




Batch
Binary Data
Database
Date Time
Insert
ResultSet
SQL
Statement
Stored Function
Table