How To Retrieve Image From Database
Retrieve image from Database
We can retrieve and store the image in the database with the use of PreparedStatement.
In JDBC, the PreparedStatement getBlob() method is used to get the binary information and it returns the object of Blob. We can get the array of the binary information, which can be written into the image file after calling thegetBytes() method on the blob object.
Syntax of getBlob() method of PreparedStatement
public Blob getBlob()throws SQLException
Syntax of getBytes() method of Blob interface
public byte[] getBytes(long pos, int length)throws SQLException
Example
CREATE TABLE "IMAGETABLE"
( "NAME" VARCHAR2(2000),
"PHOTO" BLOB
)
Let’s see an example.
Code
- import java.sql.*;
- import java.io.*;
- public class StudentDatabase2 {
- public static void main(String args[]) throws Exception {
- Class.forName("org.apache.derby.jdbc.ClientDriver");
- String url = "jdbc:derby://localhost:1527/Student";
- String username = "Student";
- String password = "student";
- Connection conn = DriverManager.getConnection(url, username, password);
- PreparedStatement ps = conn.prepareStatement("select * from STUDENT.IMAGETABLE");
- ResultSet rs = ps.executeQuery();
- if (rs.next()) {
- Blob b = rs.getBlob(2);
- byte barr[] = b.getBytes(1, (int) b.length());
- FileOutputStream fout = new FileOutputStream("B:\\photos\\2014-11-02\\11.jpg");
- fout.write(barr);
- fout.close();
- }
- System.out.println("Ok");
- conn.close();
- }
- }
Output
Now, if we see the B drive, image is created.
Summary
Thus, we learnt, we can retrieve and store the image in the database with the use of PreparedStatement and also learnt, how to retrieve an image from the database in Java.