Cheap VPS & Xen Server

Residential Proxy Network - Hourly & Monthly Packages

store image

You can store images in the database in java by the help of PreparedStatement interface.

The setBinaryStream() method of PreparedStatement is used to set Binary information into the parameterIndex.

Signature of setBinaryStream method

The syntax of setBinaryStream() method is given below:

  1. 1public void setBinaryStream(int paramIndex,InputStream stream)
  2. throws SQLException
  3. 2public void setBinaryStream(int paramIndex,InputStream stream,long length)
  4. throws SQLException

For storing image into the database, BLOB (Binary Large Object) datatype is used in the table. For example:

  2.    (    “NAME” VARCHAR2(4000),
  3.     “PHOTO” BLOB
  4.    )
  5. /

Let’s write the jdbc code to store the image in the database. Here we are using d:\\d.jpg for the location of image. You can change it according to the image location.

  1. import java.sql.*;
  2. import*;
  3. public class InsertImage {
  4. public static void main(String[] args) {
  5. try{
  6. Class.forName(“oracle.jdbc.driver.OracleDriver”);
  7. Connection con=DriverManager.getConnection(
  8. “jdbc:oracle:thin:@localhost:1521:xe”,“system”,“oracle”);
  9. PreparedStatement ps=con.prepareStatement(“insert into imgtable values(?,?)”);
  10. ps.setString(1,“sonoo”);
  11. FileInputStream fin=new FileInputStream(“d:\\g.jpg”);
  12. ps.setBinaryStream(2,fin,fin.available());
  13. int i=ps.executeUpdate();
  14. System.out.println(i+” records affected”);
  15. con.close();
  16. }catch (Exception e) {e.printStackTrace();}
  17. }
  18. }

If you see the table, record is stored in the database but image will not be shown. To do so, you need to retrieve the image from the database which we are covering in the next page.