«Back to Home

Core Java

Topics

How To Store File In Database

Store file in Database
 
In JDBC, the PreparedStatement setCharacterStream() method is used to set the character information into the parameterIndex.
 
Syntax

public void setBinaryStream(int paramIndex,InputStream stream)throws SQLException
 
public void setBinaryStream(int paramIndex,InputStream stream,long length)throws SQLException
 
CLOB (Character Large Object) data type is used in the table for storing file into the database.
 
Example

CREATE TABLE "FILETABLE"
( "ID" NUMBER,
"NAME" CLOB
)
 
Let’s see an example, given below.
 
Code
  1. import java.sql.*;  
  2. import java.io.*;  
  3. public class StudentDatabase2 {  
  4.     public static void main(String args[]) throws Exception {  
  5.         Class.forName("org.apache.derby.jdbc.ClientDriver");  
  6.         String url = "jdbc:derby://localhost:1527/Student";  
  7.         String username = "Student";  
  8.         String password = "student";  
  9.         Connection conn = DriverManager.getConnection(url, username, password);  
  10.         PreparedStatement ps = conn.prepareStatement(  
  11.             "insert into filetable values(?,?)");  
  12.         File f = new File("d:\\myfile.txt");  
  13.         FileReader fr = new FileReader(f);  
  14.         ps.setInt(1101);  
  15.         ps.setCharacterStream(2, fr, (int) f.length());  
  16.         int i = ps.executeUpdate();  
  17.         System.out.println(i + " records affected");  
  18.         conn.close();  
  19.     }  
  20. }  
35

Output

36

Summary

Thus, we learnt, PreparedStatement setCharacterStream() method is used to set the character information into the parameterIndex and also learnt, how to store file in Java database.