gpt4 book ai didi

postgresql - 如何将 CSV 数据从字符串导入到 Postgres 表?

转载 作者:行者123 更新时间:2023-11-29 13:17:36 25 4
gpt4 key购买 nike

我阅读了这个解决方案 How to import CSV file data into a PostgreSQL table?如果您想从文件加载数据,这似乎没问题。

我从 API 端点下载 CSV 数据,并希望尽可能避免保存到文件。

我有一个运行此查询的 NodeJS 应用。

那么,我能否以某种方式不传递文件路径,而是传递,例如包含查询内容的字符串?

像这样:

COPY zip_codes FROM 'john,doe,1982-02-01' WITH (FORMAT csv);

最佳答案

来自 stdin 我想:

f=# create table aa(a text, b text, c date);
CREATE TABLE
f=# copy aa from stdin delimiter ',';
Enter data to be copied followed by a newline.
End with a backslash and a period on a line by itself.
>> john,doe,1982-02-01
>> \.
f=# select * from aa;
a | b | c
------+-----+------------
john | doe | 1982-02-01
(1 row)

更新

当你展示 node.js 时,你可能正在寻找 https://github.com/brianc/node-pg-copy-streams

举个例子:

js:

client.connect()
var copyFrom = require('pg-copy-streams').from;

var stream = client.query(copyFrom("COPY aa FROM STDIN DELIMITER ','"));
stream.write("john,doe,2017-02-01\n");
stream.end();
var queryresult = client.query('select * from aa', function(err,res) {
console.log(err,res.rows);
client.end();
});

输出:

C:\Users\Vao\vatest>node t.js
null [ anonymous { a: 'john', b: 'doe', c: 2017-02-01T00:00:00.000Z } ]

SQL:

f=# select * from aa;
a | b | c
------+-----+------------
john | doe | 2017-02-01
(1 row)

关于postgresql - 如何将 CSV 数据从字符串导入到 Postgres 表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46708890/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com