使用CSV数据从Postgres复制

编程入门 行业动态 更新时间:2024-10-27 00:34:53
本文介绍了使用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复制

本文发布于:2023-10-20 01:15:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1509394.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数据   CSV   Postgres

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!