PostgreSQL:Java使用CopyManager实现客户端文件COPY导入

在MySQL中,可以使用LOAD DATA INFILE和LOAD DATA LOCAL INFILE两种方式导入文本文件中的数据到数据库表中,速度非常快。其中LOAD DATA INFILE使用的文件要位于MySQL所在服务器上,LOAD DATA LOCAL INFILE则使用的是客户端的文件。

LOAD DATA INFILE 'data.txt' INTO TABLE table_name;
LOAD DATA LOCAL INFILE 'data.txt' INTO TABLE table_name;

在PostgreSQL中也可以导入相同类型的文本文件,使用的是COPY命令:

COPY table_name FROM 'data.txt';

但是这个语句只能导入PostgreSQL所在服务器上的文件,要想导入客户端文件,就需要使用下面的语句:

COPY table_name FROM STDIN;

    public void copyFromFile(Connection connection, String filePath, String tableName) 
            throws SQLException, IOException {
        
        FileInputStream fileInputStream = null;
 
        try {
            CopyManager copyManager = new CopyManager((BaseConnection)connection);
            fileInputStream = new FileInputStream(filePath);
            copyManager.copyIn("COPY " + tableName + " FROM STDIN", fileInputStream);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

另外,还可以使用COPY table_name TO STDOUT来导出数据文件到本地,和上面的导入相反,可以用于数据库备份。此外,还支持导出一个SQL查询结果:
COPY (SELECT columns FROM table_name WHERE ……) TO STDOUT;

Java代码如下:

    public void copyToFile(Connection connection, String filePath, String tableOrQuery) 
            throws SQLException, IOException {
        
        FileOutputStream fileOutputStream = null;
 
        try {
            CopyManager copyManager = new CopyManager((BaseConnection)connection);
            fileOutputStream = new FileOutputStream(filePath);
            copyManager.copyOut("COPY " + tableOrQuery + " TO STDOUT", fileOutputStream);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
// 将本地d:/data.txt文件中的数据导入到person_info表中
copyFromFile(connection, "d:/data.txt", "person_info");
// 将person_info中的数据导出到本地文件d:/data.txt
copyToFile(connection, "d:/data.txt", "person_info");
// 将SELECT p_name,p_age FROM person_info查询结果导出到本地文件d:/data.txt
copyToFile(connection, "d:/data.txt", "(SELECT p_name,p_age FROM person_info)");

 https://blog.csdn.net/xiao__gui/article/details/12090341

原文地址:https://www.cnblogs.com/felixzh/p/10150120.html