如何从.csv文件将数据播种到postgres数据库表?

时间:2017-09-24 21:32:31

标签: node.js postgresql csv

我正在尝试从.csv文件将数据播种到psql表中。 这是设置:

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

我正在使用Node中的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不是函数错误。

1 个答案:

答案 0 :(得分:2)

它应该可以正常工作。

创建表格

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

将CSV文件中的数据复制到表格中

COPY my_table FROM '/path/to/csv/my_table.txt' WITH (FORMAT csv);