Tuesday, 8 May 2018

Download any file from Database

package com.edu.main;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class DownloadFileFromDB {

public static void main(String[] args) {

final String host = "jdbc:oracle:thin:@<host>:1521:<service_name>";
final String user = "username";
final String pass = "*******";
String SQL = "SELECT <COLUMN> FROM <TABLE> WHERE <COLUMN>=?";

Connection conn = null;
PreparedStatement smt = null;
InputStream input = null;
FileOutputStream output = null;
ResultSet rs = null;

try {

Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(host, user, pass);
System.out.println("DB Connection successful..");

smt = conn.prepareStatement(SQL);
smt.setString(1, "<VALUE_TO_BE_REPLACED_WITH_?>");
rs = smt.executeQuery();

output = new FileOutputStream(new File("C:\\Users\\bismaya\\Desktop\\<FILENAME>.<EXT>"));

while (rs.next()) {
input = rs.getBinaryStream("<COLUMN_OF_FILE_IN_DB>");
int r = 0;
while ((data = input.read()) != -1) {
output.write(data);
}
}
System.out.println("Success...");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
System.err.println("DB Connection failed!");
e.printStackTrace();
} catch (FileNotFoundException e) {
System.err.println("File not found in provided location!");
e.printStackTrace();
} catch (IOException e) {
System.err.println("Error while writing to file!");
e.printStackTrace();
} finally {
if (rs != null) {
try {
input.close();
output.flush();
output.close();
smt.close();
conn.close();
} catch (SQLException e) {
System.err.println("Error while closing the connecton!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
}

}

No comments:

Post a Comment

Thank You for your valuable comment

Difference between class level and object locking and static object lock

1) Class level locking will lock entire class, so no other thread can access any of other synchronized blocks. 2) Object locking will lo...