java实现csv导入pg数据库

 /**
     * 
     * @param filePath  文件路径
     * @param table   数据库表名
     * @param header  是否忽略文件头部
     * @param dbName  数据库名
     * @throws Exception
     */
 public static void copyFromFile(String filePath, String table, String header, String dbName)
            throws Exception {
        FileInputStream fileInputStream = null;
        Connection conn = null;
        BufferedReader file = null;
        try {
            conn = JDBCTools.getConnection(dbName);
            CopyManager copyManager = new CopyManager((BaseConnection) conn);
            fileInputStream = new FileInputStream(filePath);
            String charsetName = getFilecharset(new File(filePath));
            System.out.println("charsetName = " + charsetName);
            file = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), charsetName));
            //copy testdatafrom 'd:/test/testdata.csv' delimiter as',' csv quote as '"'
            String sql = "COPY " + table + "  FROM STDIN  delimiter as',' csv quote as '\"'  " + header + " ";
            System.out.println("sql = " + sql);
            copyManager.copyIn(sql, file);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            file.close();
            JDBCTools.releaseDB(null, null, conn);
            System.out.println("执行完成");
        }
    }

版权声明:本文为qq_38278982原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。