Skip to content

Instantly share code, notes, and snippets.

@fgabolde
Created March 20, 2014 11:05
Show Gist options
  • Save fgabolde/9661451 to your computer and use it in GitHub Desktop.
Save fgabolde/9661451 to your computer and use it in GitHub Desktop.
Dump database query to CSV
#!/usr/bin/env perl
use strict;
use warnings;
use 5.010;
use Carp;
use autodie;
use utf8;
use DBI;
use Text::CSV;
my $sth = DBI->connect(q{dbi:SQLite:foo.db},
{ RaiseError => 1 })->prepare(q{SELECT foo, baz FROM bar WHERE baz = ?});
$sth->execute('pony!');
# also set custom delimiters here if needed
my $csv = Text::CSV->new({ binary => 1 });
$csv->eol("\r\n");
open my $fh, '>:encoding(utf8)', '/tmp/foobar.csv';
while (my $data = $sth->fetchrow_arrayref) {
$csv->print($fh, $data);
}
close $fh;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment