Re: Load a csv file into a pgsql table

From: Scott Marlowe <smarlowe(at)g2switchworks(dot)com>
To: Brandon Aiken <BAiken(at)winemantech(dot)com>
Cc: emilu(at)encs(dot)concordia(dot)ca, pgsql general <pgsql-general(at)postgresql(dot)org>
Subject: Re: Load a csv file into a pgsql table
Date: 2006-09-19 18:47:24
Message-ID: 1158691644.997.189.camel@state.g2switchworks.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Tue, 2006-09-19 at 13:27, Brandon Aiken wrote:
> Define 'quick'.
>
> You could write a script that would transform a .csv file into an INSERT
> statement and save it to an .sql file.
>
> Or I suppose you could do silly ODBC stuff with MS Access.
>
> --
> Brandon Aiken
> CS/IT Systems Engineer
>
> -----Original Message-----
> From: pgsql-general-owner(at)postgresql(dot)org
> [mailto:pgsql-general-owner(at)postgresql(dot)org] On Behalf Of Emi Lu
> Sent: Tuesday, September 19, 2006 2:15 PM
> To: PgSQL General
> Subject: [GENERAL] Load a csv file into a pgsql table
>
> Greetings,
>
>
> *Except* copy command, are there other quick ways to load data from a
> csv file into a pgsql table please?

Haven't seen the OP go by, but here's the one of the simplest csv
loaders ever created. No guarantees to suitability implied or
otherwise.

#!/usr/bin/php -q
<?php
$tablename = $argv[1];
$filename = $argv[2];
if ($argc!=3){
echo "Usage:\n\n loadpg tablename filename\n";
exit;
}
if (!file_exists($filename)){
die ("given filename doesn't exist\n");
}
print "copy $tablename from stdin;\n";
$fp = fopen($filename,"r");
while(!feof($fp)){
$line = fgetcsv($fp,4096);
if (strlen($line)==0) continue(1);
print implode("\t",$line);
print "\n";
}
print '\.';
print "\n";
?>

Note that you just redirect the output to psql and off you go.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Emi Lu 2006-09-19 18:55:34 Re: Load a csv file into a pgsql table
Previous Message Brandon Aiken 2006-09-19 18:27:40 Re: Load a csv file into a pgsql table