2017-10-12 121 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) 
從標準輸入