Advertisement
Guest User

Untitled

a guest
Jun 21st, 2017
491
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.FileOutputStream;
  3. import java.io.InputStream;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.sql.Statement;
  9.  
  10. /**
  11. *
  12. * @author www.luv2code.com
  13. *
  14. */
  15. public class ReadBlobDemo {
  16.  
  17. public static void main(String[] args) throws Exception {
  18.  
  19. Connection myConn = null;
  20. Statement myStmt = null;
  21. ResultSet myRs = null;
  22.  
  23. InputStream input = null;
  24. FileOutputStream output = null;
  25.  
  26. try {
  27. // 1. Get a connection to database
  28. myConn = DriverManager.getConnection(
  29. "jdbc:mysql://localhost:3306/demo", "student", "student");
  30.  
  31. // 2. Execute statement
  32. myStmt = myConn.createStatement();
  33. String sql = "select resume from employees where email='john.doe@foo.com'";
  34. myRs = myStmt.executeQuery(sql);
  35.  
  36. // 3. Set up a handle to the file
  37. File theFile = new File("resume_from_db.pdf");
  38. output = new FileOutputStream(theFile);
  39.  
  40. if (myRs.next()) {
  41.  
  42. input = myRs.getBinaryStream("resume");
  43. System.out.println("Reading resume from database...");
  44. System.out.println(sql);
  45.  
  46. byte[] buffer = new byte[1024];
  47. while (input.read(buffer) > 0) {
  48. output.write(buffer);
  49. }
  50.  
  51. System.out.println("\nSaved to file: " + theFile.getAbsolutePath());
  52.  
  53. System.out.println("\nCompleted successfully!");
  54. }
  55.  
  56. } catch (Exception exc) {
  57. exc.printStackTrace();
  58. } finally {
  59. if (input != null) {
  60. input.close();
  61. }
  62.  
  63. if (output != null) {
  64. output.close();
  65. }
  66.  
  67. close(myConn, myStmt);
  68. }
  69. }
  70.  
  71. private static void close(Connection myConn, Statement myStmt)
  72. throws SQLException {
  73.  
  74. if (myStmt != null) {
  75. myStmt.close();
  76. }
  77.  
  78. if (myConn != null) {
  79. myConn.close();
  80. }
  81. }
  82. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement