Guest User

Untitled

a guest
Dec 14th, 2018
151
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.76 KB | None | 0 0
  1. package edu.mayo.nlp;
  2. import java.io.File;
  3. import java.io.IOException;
  4. import java.nio.file.Files;
  5. import java.nio.file.Path;
  6. import java.nio.file.Paths;
  7. import java.sql.*;
  8. import java.util.stream.Stream;
  9.  
  10. public class PostgreSqlXmlTest {
  11.  
  12. Connection conn = null;
  13. PreparedStatement stmt = null;
  14.  
  15. int docId = 10000;
  16.  
  17. private void connectServer(){
  18. try {
  19.  
  20. Class.forName("org.postgresql.Driver");
  21. conn = DriverManager
  22. .getConnection("jdbc:postgresql://localhost:5432/postgres",
  23. "postgres", "19891024");
  24.  
  25. conn.setAutoCommit(true);
  26. System.out.println("Opened database successfully");
  27. } catch (ClassNotFoundException e) {
  28. e.printStackTrace();
  29. } catch (SQLException e) {
  30. e.printStackTrace();
  31. }
  32. }
  33.  
  34. public String readXmlPath(Path xmlPath){
  35. try {
  36. return new String(Files.readAllBytes(xmlPath));
  37. } catch (IOException e) {
  38. e.printStackTrace();
  39. }
  40. return "";
  41. }
  42.  
  43. public void insertCdmXml(Path rootDir){
  44. File[] cdmXmlList = rootDir.toFile().listFiles();
  45. String sql = "INSERT INTO cdm_xml(doc_id, xml_content) VALUES (?, XMLPARSE(DOCUMENT ?))";
  46.  
  47. connectServer();
  48. try {
  49. for (File file : cdmXmlList) {
  50. if (file.isFile()) {
  51. stmt = conn.prepareStatement(sql);
  52. stmt.setInt(1, docId++);
  53. stmt.setString(2, readXmlPath(file.toPath()));
  54. int i = stmt.executeUpdate();
  55. System.out.println(i + " records inserted");
  56. System.out.println("Inserted records into the table: " + file);
  57. docId += 1;
  58. }
  59. }
  60. } catch (SQLException e) {
  61. if (conn != null) {
  62. try {
  63. System.err.print("Transaction is being rolled back");
  64. conn.rollback();
  65. } catch (SQLException excep) {
  66. e.printStackTrace();
  67. }
  68. }
  69. }
  70.  
  71. closeConn();
  72. }
  73.  
  74.  
  75. private void closeConn(){
  76. try {
  77. if(stmt != null)
  78. stmt.close();
  79. if(conn != null)
  80. conn.close();
  81. } catch (SQLException e) {
  82. e.printStackTrace();
  83. }
  84. }
  85.  
  86. public static void main(String args[]) {
  87. PostgreSqlXmlTest ptest = new PostgreSqlXmlTest();
  88.  
  89. Path rootDir = Paths.get("/Users/m142167/projects/cdm/cdm_use_case/ivf/reports");
  90. ptest.insertCdmXml(rootDir);
  91.  
  92. rootDir = Paths.get("/Users/m142167/projects/cdm/cdm_use_case/breastCancer/reports");
  93. ptest.insertCdmXml(rootDir);
  94.  
  95. }
  96. }
Add Comment
Please, Sign In to add comment