Correct way to use copy Postgres jdbc

前端 未结 2 1516
面向向阳花
面向向阳花 2020-12-31 23:27

Unable to use copy command with jdbc Postgres. Whats wrong with the below code snippet sample.

public boolean loadReportToDB(String date) {
        // TODO A         


        
相关标签:
2条回答
  • 2020-12-31 23:58

    As your input file is stored locally on the computer running your Java program you need to use the equivalent of copy ... from stdin in JDBC because copy can only access files on the server (where Postgres is running).

    To do that use the CopyManager API provided by the JDBC driver.

    Something along the lines:

    Connection connection = DBUtil.getConnection("POSTGRES");
    
    String fileName = "C:/_0STUFF/NSE_DATA/nseoi_" + date + ".csv";
    String sql = "copy fno_oi FROM stdin DELIMITER ',' CSV header";
    
    BaseConnection pgcon = (BaseConnection)conection;
    CopyManager mgr = new CopyManager(pgcon);
    
    try {
    
      Reader in = new BufferedReader(new FileReader(new File(fileName)));
      long rowsaffected  = mgr.copyIn(sql, in);
    
      System.out.println("Rows copied: " + rowsaffected);
    
    } catch (SQLException e) {
      e.printStackTrace();
    }
    
    0 讨论(0)
  • 2021-01-01 00:00

    This works for me:

    try (Connection conn = DriverManager.getConnection(connUrl, myUid, myPwd)) {
        long rowsInserted = new CopyManager((BaseConnection) conn)
                .copyIn(
                    "COPY table1 FROM STDIN (FORMAT csv, HEADER)", 
                    new BufferedReader(new FileReader("C:/Users/gord/Desktop/testdata.csv"))
                    );
        System.out.printf("%d row(s) inserted%n", rowsInserted);
    }
    

    Using copyIn(String sql, Reader from) has the advantage of avoiding issues where the PostgreSQL server process is unable to read the file directly, either because it lacks permissions (like reading files on my Desktop) or because the file is not local to the machine where the PostgreSQL server is running.

    0 讨论(0)
提交回复
热议问题