Read an Image in JDBC Example

By | 2018-04-12T21:40:19+00:00 June 27th, 2016|jdbc|0 Comments

Here is an example for how to read an image in JDBC. In the previous example, we insert an image using JDBC. Now in this example we are going to read that image from database. If you are not coming through the previous example, it is recommended to read once insert an image using JDBC.

As we already discussed in the previous tutorial, reading an image is nothing but reading binary data. For read operations in JDBC we can use the executeQuery() method on statement.

executeQuery() method returns the ResultSet object. It contains the data rows. Usually we can read the data from ResultSet using getXXX() methods.

But here, in our example we are not reading an ordinary data. We are going to retrieve an image i.e binary data. To read the binary objects, ResultSet given us getBinaryStream(String col) method.

To call the getBinaryStream() method, we need to pass the column name of BOLB type in database, in our case it “photo”.

InputStream is = rs.getBinaryStream("photo");

Here is the complete example for read an image in jdbc.

Read an Image in JDBC Example :

class JDBC_Getting_LargeObjects_Example {

    public static void main(String[] args) throws Exception {

        Connection connection = null;
        Statement stmt = null;

        try {
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/jdbc", "root", "123456");
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select * from employee");
            if ( {
                InputStream is = rs.getBinaryStream("photo");
                FileOutputStream fos = new FileOutputStream(
                int bytesRead = 0;
                byte[] buffer = new byte[4096];
                while ((bytesRead = != -1) {
                    fos.write(buffer, 0, bytesRead);

            System.out.println("Image created");

        } catch (Exception e) {

By run this example, you can find an image in your desired folder.

Happy Learning 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment