Insert File JDBC

To store a file in Oracle table though JDBC (Insert File JDBC)

Before going into execution, create table by name office with columns FILEID (number) and FILENAME (CLOB).

Example on Insert File JDBC
import java.sql.*;
public class FileInsert
{
  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 office values(?, ?)");

    File f1 = new File("C:\\expenditure.txt");  
    FileReader fr1 = new FileReader(f1);  

    pst.setInt(1, 1000);                                // FILEID is 1000,  1 represents first question mark
    pst.setCharacterStream(2, fr1, (int) f1.length());  // 2 represents second question mark
    int recordsAffected = pst.executeUpdate();  
    System.out.println(recordsAffected + " records inserted");  

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

To write to a CLOB (Character Large Object) data type, The PreparedStatement interface comes with three methods.

  1. void setCharacterStream(int parameterIndex, Reader reader) throws SQLException
  2. void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException
  3. void setCharacterStream(int parameterIndex, Reader reader, long length) throws SQLException

In the above code, the second method is used.

pst.setCharacterStream(2, fr1, (int) f1.length());

f1.length() returns the size of the file as a long data type which casted to int data type. fr1 represents FileReader object holding the reference of expenditure.txt file. Otherway to say, to write the complete file.

For storing images, setBinaryStream() method is to be used and to retrieve image getBinaryStream().

View All JDBC Examples

Leave a Comment

Your email address will not be published.