Skip to content

Instantly share code, notes, and snippets.

@thiago-vieira
Created September 26, 2020 01:26
Show Gist options
  • Save thiago-vieira/1f6c8e1d332270d5a81f49407280659e to your computer and use it in GitHub Desktop.
Save thiago-vieira/1f6c8e1d332270d5a81f49407280659e to your computer and use it in GitHub Desktop.
Download zip file from Oracle Blob column
package oracledownloadblob;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class OracleDownloadBlob {
public static void main(String[] args) {
Connection con = null;
System.out.println("start");
try {
FileOutputStream fos = new FileOutputStream("C:/fotos.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
// use ojdbc8.jar or compatible
String driver = "oracle.jdbc.driver.OracleDriver";
Class.forName(driver);
String server = "host";
String port = "1521";
String database = "db";
String url = "jdbc:oracle:thin:@" + server + ":" + port + "/" + database; // if SID use ":database" else if servicename use "/database"
String username = "username";
String password = "password";
con = DriverManager.getConnection(url, username, password);
String query = "select foto, nome from tabela";
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(query);
String nomeArquivo;
byte[] arquivo;
while (res.next()) {
arquivo = res.getBytes("foto");
nomeArquivo = res.getString("nome") + ".jpg";
try {
System.out.println(nomeArquivo);
zos.putNextEntry(new ZipEntry(nomeArquivo));
zos.write(arquivo, 0, arquivo.length);
} catch (FileNotFoundException ex) {
System.err.println("A file does not exist: " + ex);
} catch (IOException ex) {
System.err.println("I/O error: " + ex);
}
zos.closeEntry();
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
if (con != null) {
try {
con.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
System.out.println("end");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment