2017-10-12 82 views
1

我看了这个解决方案How to import CSV file data into a PostgreSQL table?,如果你想从一个文件加载数据似乎没有问题。如何将CSV数据从字符串导入到Postgres表中?

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

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

所以,我可以不通过文件路径,但例如查询内容的字符串?

事情是这样的:

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

可能.. –

回答

1

from 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) 
从标准输入
相关问题