3

I am trying to seed data into a psql table from a .csv file. This is the setup:

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

I am using the pg module in Node to connect to database grocery_store that has 1 table grocery_items with columns id, name, price and section.

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

How can I now seed data from data.csv into the grocery_items table?

I've tried the pg-copy-streams module and they suggest to do:

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);
});

But I got pg.connect is not a function error when I tried this.

3
  • Mysql is a different product. Commented Sep 24, 2017 at 21:44
  • @baibhavx did you get this to work? I am curious about the same question. Commented Dec 13, 2017 at 15:28
  • 1
    @MihirPatel \copy grocery_items(name, price, section) FROM './data.csv' DELIMITER ',' CSV HEADER; solved my problem! Commented Jan 5, 2018 at 3:31

1 Answer 1

7

It should work fine.

Create your table:

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

Copy data from your CSV file to the table:

COPY my_table FROM '/path/to/csv/my_table.txt' WITH (FORMAT csv);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.