Get Blob

In this example you will learn Blob is known as 'binary large object', is a collection of binary data stored as a single entity in a database management system and can hold variable amount of data.

Get Blob

In this example you will learn Blob is known as 'binary large object', is a collection of binary data stored as a single entity in a database management system and can hold variable amount of data.

Get Blob

Get Blob

     

Blob is known as 'binary large object', is a collection of binary data stored as a single entity in a database management system and can hold variable amount of data. Here in the example shown below we will learn how to retrieve image from mysql database which is saved as large binary object. 

Here is the video tutorial of "How to get blob image from MySQL Database?":


Description of the code:
   1.
First create connection to the database from where you want to retrieve image saved as blob.
   2. Create a mysql query to retrieve image value from table column.
   3. Retrieves the value of the designated column in the current row of this ResultSet object as a Blob object by using getBlob() method. 
   4. Write data on standard output device.

Table Structure:

CREATE TABLE pictures ( image_id
 int(10) NOT NULL auto_increment,
image blob
)

Here is the code of GetBlob.java

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

class GetBlob {
FileOutputStream image;
Connection con = null;
PreparedStatement pstmt = null;
Statement stmt= null;
ResultSet res = null;
StringBuffer query=null;
String driverName = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";;
String dbName = "register";
String userName = "root";
String password = "root";

public GetBlob(){
try{
Class.forName(driverName);
con = DriverManager.getConnection(url+dbName,userName,password);
stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from picture where image_id='3'");
if (rs.next()) {
Blob test=rs.getBlob("image");
InputStream x=test.getBinaryStream();
int size=x.available();
OutputStream out=new FileOutputStream("C:\\anu.jpg");
byte b[]= new byte[size];
x.read(b);
out.write(b);
}
}
catch(Exception e){
System.out.println("Exception :"+e);
}
finally{
try{
stmt.close();
con.close();
}
catch(Exception e){
System.out.println(e);
}
}
}
public static void main(String args[]) throws IOException{
GetBlob blob = new GetBlob();
}
}


Image retrieved from the database:

Download Source Code