Skip to content

Instantly share code, notes, and snippets.

@Tordek
Created November 22, 2010 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tordek/710449 to your computer and use it in GitHub Desktop.
Save Tordek/710449 to your computer and use it in GitHub Desktop.
CSV to SQL
#!/usr/bin/env perl
use warnings;
use strict;
# Read the first parameter: tablename.
my $tablename = shift;
# The first line holds the names of the fields.
my $fields = <>;
chomp $fields;
print "INSERT INTO $tablename ($fields) values";
my $firstline = 1;
while (<>) {
chomp;
if ($firstline) {
# The first insert is special-cased to avoid a trailing comma.
print "\n";
$firstline = 0;
} else {
# The rest of the VALUE groups are comma-separated.
print ",\n";
}
print "('" . join ("','", split(/\s*,\s*/)) . "')";
}
print ";\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment