How can we retrieve a blob datatype from a table using the getBinaryStream() method in JDBC?

The ResultSet interface provides the method named getBlob() to retrieve blob datatype from a table in the database. In addition to this, it also provides a method named getBinaryStream()

Like getBlob() this method also accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column. The difference is unlike the getBlob() method (which returns a Blob object) this method returns an InputStream object which holds the contents of the blob datatype in the form of un-interpreted bytes.


Assume we have created a table named MyTable in the database with the following description.

| Field | Type         | Null | Key | Default | Extra |
| Name  | varchar(255) | YES  |     | NULL    |       |
| image | blob         | YES  |     | NULL    |       |

And, we have inserted an image in it with name sample_image. Following program retrieves the contents of the MyTable using the getString() and getBinaryStream() methods.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class RetrievingBlob_ByteStream {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");

      //Creating a Statement object
      Statement stmt = con.createStatement();
      //retrieving the data
      ResultSet rs = stmt.executeQuery("select * from MyTable");

      int i = 0;
      System.out.println("Contents of the table");
      while( {
         InputStream inputStream = rs.getBinaryStream("image");
         byte byteArray[] = new byte[inputStream.available()];;
         FileOutputStream outPutStream = new


Connection established......
Contents of the table

Updated on: 30-Jul-2019


Kickstart Your Career

Get certified by completing the course

Get Started