JDBC retrieve file example

PreparedStatement provides the facility to store and retrieve the file in the database using JDBC.

PreparedStatement methods to retrieve file:

1. public Clob getClob(int columnIndex) throws SQLException

Example:

JDBCTest.java
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
 
import com.javawithease.util.JDBCUtil;
 
/**
* This class is used to retrieve a file from DB.
* @author javawithease
*/

public class JDBCTest {
public static void main(String args[]){
Connection conn = null;
PreparedStatement preparedStatement = null;
 
String query = "select * from FILESTORE " +
"where FILE_ID = 2";
 
try{
//get connection
conn = JDBCUtil.getConnection();
 
//create preparedStatement
preparedStatement =
conn.prepareStatement(query);
 
//execute query
ResultSet resultSet =
preparedStatement.executeQuery();
 
resultSet.next();
 
Clob clob = resultSet.getClob(2);
Reader reader = clob.getCharacterStream();
 
FileWriter fileWriter =
new FileWriter("F:\\savedFile.txt");
 
int i;
while((i=reader.read())!=-1){
fileWriter.write((char)i);
}
 
System.out.println("File retrieved successfully.");
 
//close connection
fileWriter.close();
preparedStatement.close();
conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
JDBCUtil.java
import java.sql.Connection;
import java.sql.DriverManager;
 
/**
* This is a utility class for JDBC connection.
* @author jawithease
*/

public class JDBCUtil {
//JDBC and database properties.
private static final String DB_DRIVER =
"oracle.jdbc.driver.OracleDriver";
private static final String DB_URL =
"jdbc:oracle:thin:@localhost:1521:XE";
private static final String DB_USERNAME = "system";
private static final String DB_PASSWORD = "oracle";
 
public static Connection getConnection(){
Connection conn = null;
try{
//Register the JDBC driver
Class.forName(DB_DRIVER);
 
//Open the connection
conn = DriverManager.
getConnection(DB_URL, DB_USERNAME, DB_PASSWORD);
 
if(conn != null){
System.out.println("Successfully connected.");
}else{
System.out.println("Failed to connect.");
}
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
}

Output:

Successfully connected.
File retrieved successfully.

No comments: