Skip to content

Instantly share code, notes, and snippets.

@soardex
Created May 1, 2014 10:56
Show Gist options
  • Save soardex/227e23f18ac459372667 to your computer and use it in GitHub Desktop.
Save soardex/227e23f18ac459372667 to your computer and use it in GitHub Desktop.
Save CVS contents to MySQL database.
use strict;
use warnings;
use DBI;
sub trim {
my $s = shift;
$s =~ s/^"|"$//g;
$s =~ s/^\s+|\s+$//g;
return $s;
}
my $dsn = 'dbi:mysql:dbname=kohana;host=localhost;port=3306';
my $dbh = DBI->connect($dsn, 'root', '', {AutoCommit=>1, RaiseError=>1, PrintError=>0});
my $file = 'companylist.csv';
my @data;
open(my $fh, '<', $file) or die "Can't read '$file' [$!]\n";
while (my $line = <$fh>) {
chomp $line;
my @fields = split(/,/, $line);
push @data, \@fields;
}
for (my $i = 1; $i <= $#data; $i++) {
$dbh->do('INSERT INTO stock_symbols (company_id, company_name, company_symbol, company_details) VALUES (0, ?, ?, ?)',
undef,
trim($data[$i][1]), # Name
trim($data[$i][0]), # Symbol
trim($data[$i][7]), # Industry
);
}
$dbh->disconnect();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment