
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Retrieve BLOB DataType using 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.
Example
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.io.FileOutputStream; import java.io.InputStream; 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(rs.next()) { System.out.println(rs.getString("Name")); InputStream inputStream = rs.getBinaryStream("image"); byte byteArray[] = new byte[inputStream.available()]; inputStream.read(byteArray); FileOutputStream outPutStream = new FileOutputStream("E:\images\blob_output"+i+".jpg"); outPutStream.write(byteArray); System.out.println("E:\images\blob_output"+i+".jpg"); } } }
Output
Connection established...... Contents of the table sample_image E:\images\blob_output0.jpg