使用CSV数据从Postgres复制 [英] Postgres Copy from Variable with CSV data

查看:158
本文介绍了使用CSV数据从Postgres复制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道您可以从文件运行这样的复制命令:

I know you can run a copy command like this from a file:

"COPY zip_codes FROM '/path/to/csv/ZIP_CODES.txt' DELIMITER ',' CSV;"

我想从ruby变量中复制csv数据,所以我可以这样做

I'd like to copy csv data from a ruby variable so I can do like so

"COPY zip_codes FROM '#{csv_data}' DELIMITER ',' CSV;"


推荐答案

SQL COPY 命令。 COPY 仅从文件 STDIN 复制。

That's not possible with the SQL COPY command. COPY only copies from a file or STDIN.

您可以将变量的内容写入文件,也可以通过STDIN将其传递。仅适用于几行以上。

You can either write the content of the variable to a file or pipe it via STDIN. Only makes sense for more than a couple of rows.

我想我在更新之前误解了您的问题,您可能不知道不需要:

I think I misunderstood your question before the update, you probably don't need this:

文件路径无法像其他数据项一样交换,因此您不能使用准备好的语句。在执行或诉诸动态SQL之前,先通过服务器端函数构建 whole 语句,

The file path can not be exchanged like other data items, and you can't use a prepared statement for that. Build the whole statement before executing or resort to dynamic SQL with a server-side function like:

CREATE OR REPLACE FUNCTION f_cp(_file text)
  RETURNS void AS
$BODY$
BEGIN
EXECUTE format($$COPY zip_codes FROM %L DELIMITER ',' CSV$$, $1);
END
$BODY$
  LANGUAGE plpgsql;

致电:

SELECT f_cp('/var/lib/postgres/sync/myfile.csv')

format() 需要Postgres 9.1或更高版本。

format() requires Postgres 9.1 or later.

这篇关于使用CSV数据从Postgres复制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆