Insert Image JDBC

Insert Image JDBC : In this code, an image is inserted into table with JDBC. The table name is "marriage" and column name is "photo". So, by the time this program is executed, create a table marriage and a column photo of data type "long raw". For images, I/O streams are used.
Example on Insert Image JDBC
import java.sql.*;
import java.io.*;
public class InsertImage
{
  public static void main(String args[]) throws Exception
  {
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    Connection con=DriverManager.getConnection("jdbc:odbc:snrao", "scott","tiger");
    PreparedStatement pst=con.prepareStatement("insert into marriage values(?)");

    FileInputStream fis = new FileInputStream("juggler.gif");
    pst.setBinaryStream(1, fis, fis.available());             // prepare for Insert Image JDBC

    pst.executeUpdate();                                      // Insert Image JDBC is done here

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

    fis.close();
    pst.close();
    con.close();
  }
}

Here, available() method of FileInputStream returns the size of the image juggler.gif in bytes.

pst.setBinaryStream(1, fis, fis.available()): 1 indicates the question mark, fis indicates the file juggler.gif and available() gives the size of juggler.gif. With the above code, juggler.gif is inserted into marriage table.

Let us read back and print the image and is shown in Retrieving Image with JDBC.

Pass your comments and suggestions to improve this tutorial "Insert Image JDBC".

1 thought on “Insert Image JDBC”

  1. Logeshwari babu

    from where the image will be uploaded? please provide clear path about it
    and please provide step by step explanation for this example

Leave a Comment

Your email address will not be published.