Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package edu.mayo.nlp;
- import java.io.File;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.sql.*;
- import java.util.stream.Stream;
- public class PostgreSqlXmlTest {
- Connection conn = null;
- PreparedStatement stmt = null;
- int docId = 10000;
- private void connectServer(){
- try {
- Class.forName("org.postgresql.Driver");
- conn = DriverManager
- .getConnection("jdbc:postgresql://localhost:5432/postgres",
- "postgres", "19891024");
- conn.setAutoCommit(true);
- System.out.println("Opened database successfully");
- } catch (ClassNotFoundException e) {
- e.printStackTrace();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public String readXmlPath(Path xmlPath){
- try {
- return new String(Files.readAllBytes(xmlPath));
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "";
- }
- public void insertCdmXml(Path rootDir){
- File[] cdmXmlList = rootDir.toFile().listFiles();
- String sql = "INSERT INTO cdm_xml(doc_id, xml_content) VALUES (?, XMLPARSE(DOCUMENT ?))";
- connectServer();
- try {
- for (File file : cdmXmlList) {
- if (file.isFile()) {
- stmt = conn.prepareStatement(sql);
- stmt.setInt(1, docId++);
- stmt.setString(2, readXmlPath(file.toPath()));
- int i = stmt.executeUpdate();
- System.out.println(i + " records inserted");
- System.out.println("Inserted records into the table: " + file);
- docId += 1;
- }
- }
- } catch (SQLException e) {
- if (conn != null) {
- try {
- System.err.print("Transaction is being rolled back");
- conn.rollback();
- } catch (SQLException excep) {
- e.printStackTrace();
- }
- }
- }
- closeConn();
- }
- private void closeConn(){
- try {
- if(stmt != null)
- stmt.close();
- if(conn != null)
- conn.close();
- } catch (SQLException e) {
- e.printStackTrace();
- }
- }
- public static void main(String args[]) {
- PostgreSqlXmlTest ptest = new PostgreSqlXmlTest();
- Path rootDir = Paths.get("/Users/m142167/projects/cdm/cdm_use_case/ivf/reports");
- ptest.insertCdmXml(rootDir);
- rootDir = Paths.get("/Users/m142167/projects/cdm/cdm_use_case/breastCancer/reports");
- ptest.insertCdmXml(rootDir);
- }
- }
Add Comment
Please, Sign In to add comment