package homeWork;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class savePdf {
private static final String URL_STR="jdbc:postgresql://localhost:5432/prototype";
private static final String DRIVER_STR="org.postgresql.Driver";
public static void main(String[] args) throws FileNotFoundException, Exception, SQLException {
File file = new File("/Users/tk/input.pdf");
FileInputStream fis = new FileInputStream(file);
savePdf sv = new savePdf();
int retCode1 = sv.savePdf(file,fis);
@SuppressWarnings("unused")
int retCode2 = sv.getPdf(0);
}
PDF save
@param file
@param pdf
@return
@throws ClassNotFoundException
@throws SQLException
@throws Exception
@SuppressWarnings("unused")
private int savePdf(File file,FileInputStream pdf) throws ClassNotFoundException, SQLException, Exception {
Connection conn = null;
String url = URL_STR;
String user = "tk";
String password = "";
Class.forName(DRIVER_STR);
conn = DriverManager.getConnection(url, user, password);
PreparedStatement ps = conn.prepareStatement("INSERT INTO storedPdf VALUES (?, ?, ?)");
ps.setInt(1, 0);
ps.setString(2, "samplefile");
ps.setBinaryStream(3, pdf, (int)file.length());
ps.executeUpdate();
ps.close();
pdf.close();
return 0;
}
@param key
@return
@throws Exception
private int getPdf(int key) throws Exception {
Connection conn = null;
String url = URL_STR;
String user = "tk";
String password = "";
Class.forName(DRIVER_STR);
conn = DriverManager.getConnection(url, user, password);
PreparedStatement ps = conn.prepareStatement("SELECT pdf FROM storedPdf WHERE id = ?");
ps.setInt(1, 0);
ResultSet rs = ps.executeQuery();
FileOutputStream fos = new FileOutputStream("/Users/tk/output.pdf");
while (rs.next())
{
byte[] imgBytes = rs.getBytes(1);
fos.write(imgBytes, 0, imgBytes.length);
}
rs.close();
ps.close();
return 0;
}
}