«Back to Home

Core Java

Topics

How To Retrieve File From Database

Retrieve file from Database
 
In JDBC, the PreparedStatement getClob() method is used to get the file information from the database.
 
Syntax of getClob method

public Clob getClob(int columnIndex){}
 
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("select * from filetable");  
  11.         ResultSet rs = ps.executeQuery();  
  12.         rs.next();  
  13.         Clob c = rs.getClob(2);  
  14.         Reader r = c.getCharacterStream();  
  15.         FileWriter fw = new FileWriter("d:\\retrivefile.txt");  
  16.         int i;  
  17.         while ((i = r.read()) != -1) {  
  18.             fw.write((char) i);  
  19.         }  
  20.         fw.close();  
  21.         conn.close();  
  22.         System.out.println("Ok");  
  23.     }  
  24. }  
1

Output

2

Summary

Thus, we learnt, PreparedStatement getClob() method is used to get file information from the database and also learnt, how to retrieve the file from the database in Java.