Wednesday , June 28 2017
Home / jdbc / Read an Image in JDBC Example

Read an Image in JDBC Example

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 {
            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 run this example, you can find an image in your desired folder.

Happy Learning 🙂

About chandrashekhar

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+ ,

Check Also

JDBC Updatable ResultSet Example

Whenever we create a ResultSet object which never allows us to update the database through …

Leave a Reply

Your email address will not be published. Required fields are marked *