What is JDBC Blob data type? how to store and read data from it?

JDBCJava 8MySQLMySQLi Database

A BLOB is binary large object that can hold a variable amount of data with a maximum length of 65535 characters.

These are used to store large amounts of binary data, such as images or other types of files. Fields defined as TEXT also hold large amounts of data. The difference between the two is that the sorts and comparisons on the stored data are case sensitive on BLOBs and are not case sensitive in TEXT fields. You do not specify a length with BLOB or TEXT.

Storing blob in to database

To store Blob datatype to database, using JDBC program follow the steps given below

Step 1: Connect to the database

You can connect to a database using the getConnection() method of the DriverManager class.

Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");

Step 2: Create a Prepared statement

Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter.

PreparedStatement pstmt = con.prepareStatement("INSERT INTO MyTableVALUES(?, ?)");

Step 3: Set values to the place holders

Set the values to the place holders using the setter methods of the PreparedStatement  interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method.

And if it is of Blob type you can set value to it using the setBinaryStream() or setBlob() methods. To these methods pass an integer variable representing the parameter index and an object of InputStream class as parameters.

pstmt.setString(1, "sample image");
//Inserting Blob type
InputStream in = new FileInputStream("E:\\images\\cat.jpg");
pstmt.setBlob(2, in);

Step 4: Execute the statement

Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.

Retrieving blob from database

The getBlob() method of the ResultSet interface 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 and returns it in the form of a Blob object.

while(rs.next()) {
   rs.getString("Name");
   rs.getString("Type");
   Blob blob = rs.getBlob("Logo");
}

The getBytes() method of the Blob Interface retrieves the contents of the current Blob object and returns as a byte array.

Using the getBlob() method you can get the contents of the blob in to a byte array and create an image using the write() method of the FileOutputStream object.

byte byteArray[] = blob.getBytes(1,(int)blob.length());
FileOutputStream outPutStream = new FileOutputStream("path");
outPutStream.write(byteArray);

Example

Following example creates a table in MySQL database with blob datatype, inserts image to it. Retrieves it back and stores in the local file system.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class BlobExample {
   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 table
      Statement stmt = con.createStatement();
      stmt.execute("CREATE TABLE SampleTable( Name VARCHAR(255), Image BLOB)");
      System.out.println("Table Created");
      //Inserting values
      String query = "INSERT INTO SampleTable(Name,image) VALUES (?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "sample image");
      FileInputStream fin = new FileInputStream("E:\\images\\cat.jpg");
      pstmt.setBlob(2, fin);
      pstmt.execute();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from SampleTable");
      int i = 1;
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println(rs.getString("Name"));
         Blob blob = rs.getBlob("Image");
         byte byteArray[] = blob.getBytes(1,(int)blob.length());
         FileOutputStream outPutStream = new
         FileOutputStream("E:\\images\\blob_output"+i+".jpg");
         outPutStream.write(byteArray);
         System.out.println("E:\\images\\blob_output"+i+".jpg");
         System.out.println();
         i++;
      }
   }
}

Output

Connection established......
Table Created
Contents of the table are:
sample image
E:\images\blob_output1.jpg
raja
Published on 22-Mar-2019 15:28:14
Advertisements