java使用copy in 的方式把数据导入postgres或greenplum

copy in

postgres导入数据的时候可以使用cpoy 命令进行数据导入,如果使用java操作copy命令则需要使用postgres提供的jdbc驱动中的CopyManager来实现
  • 封装一下
public class PGCopyInUtils {


    /**
     * 将表中的数据导出到本地文件
     *
     * @param connection   连接
     * @param filePath     文件路径
     * @param tableOrQuery 表名 或者查询语句
     * @throws SQLException SQLException
     * @throws IOException  IOException
     */
    public static 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);
            String copyOut = "COPY " + tableOrQuery + " TO STDOUT DELIMITER AS ','";
            final long line = copyManager.copyOut(copyOut, fileOutputStream);
            System.out.println(line);
        } finally {
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将文件中的数据导入到数据库中
     *
     * @param connection 连接
     * @param filePath   文件路径
     * @param tableName  表名
     * @throws SQLException SQLException
     * @throws IOException  IOException
     * @return long  导入的行数
     */
    public static long copyFromFile(Connection connection, String filePath, String tableName)
            throws SQLException, IOException {
        FileInputStream fileInputStream = null;
        try {
            CopyManager copyManager = new CopyManager((BaseConnection) connection);
            fileInputStream = new FileInputStream(filePath);
            String copyIn = "COPY " + tableName + " FROM STDIN DELIMITER AS ','";
            return copyManager.copyIn(copyIn, fileInputStream);
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
  • 使用
1. connection 数据库连接
2. 文件路径
3. 表名
PGCopyInUtils.copyFromFile(connection, Constants.COPY_DEVICE_DATA_FILE_PATH, Constants.TABLE_NAME);
  • 注意
以上文件内容的分隔符为"," 标准输入.
  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值