Read an Image in JDBC Example

By | 2018-10-30T10:35:22+05:30 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 the 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 reading operations in JDBC, we can use the executeQuery() method on a 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 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 :

JDBC_Getting_LargeObjects_Example.java
public class JDBC_Getting_LargeObjects_Example {

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

        Connection connection = null;
        Statement stmt = null;

        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            connection = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/jdbc", "root", "123456");
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery("select * from employee");
            if (rs.next()) {
                InputStream is = rs.getBinaryStream("photo");
                FileOutputStream fos = new FileOutputStream(
                        "C:/Users/cgoka/Desktop/sample_NEW.jpg");
                int bytesRead = 0;
                byte[] buffer = new byte[4096];
                while ((bytesRead = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                is.close();
                fos.close();
            }

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

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

By running 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