Created
May 1, 2014 10:56
-
-
Save soardex/227e23f18ac459372667 to your computer and use it in GitHub Desktop.
Save CVS contents to MySQL database.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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