2017-09-24 244 views
0

我想從.csv文件中將數據種入psql表。 這是設置:如何將數據從.csv文件中導入到postgres數據庫表中?

data.csv:
name,price,section Aluminum Foil,8.84,miscellaneous Apples,10.81,produce

我正在使用節點的pg模塊來連接數據庫grocery_store有1臺grocery_items的列id, name, price and section

const Client = require('pg').Client 
const connectionString = 'postgresql://localhost:5432/grocery_store' 
const pg = new Client({ connectionString: connectionString }) 

如何從data.csv我現在種子數據到grocery_items表?

我已經試過pg-copy-streams模塊和他們建議做:

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

pg.connect(function(err, client, done) { 
    var stream = client.query(copyFrom('COPY my_table FROM STDIN')); 
    var fileStream = fs.createReadStream('some_file.tsv') 
    fileStream.on('error', done); 
    fileStream.pipe(stream).on('finish', done).on('error', done); 
}); 

但我得到pg.connect不是一個函數錯誤,當我嘗試這樣做。

+0

MySQL是不同的產品。 – Shadow

+0

@baibhavx你是否得到這個工作?我對同一個問題感到好奇。 –

+1

@MihirPatel'\ copy grocery_items(name,price,section)FROM'./data.csv'DELIMITER','CSV HEADER;'解決了我的問題! – baibhavx

回答

1

它應該工作正常。

創建表:從CSV

CREATE TABLE my_table 
(name varchar(50), price int, section varchar(50)); 

複製數據文件到表:

COPY my_table FROM '/path/to/csv/my_table.txt' WITH (FORMAT csv); 
相關問題