Load a csv file into a database (for example, mysql). The first line of the csv are the field names where data will be inserted (in order), and the rest, records to be inserted. It is similar to mysqlimport.
#!/usr/bin/perl -w use strict; use DBI; use Text::CSV; my $file = shift or die "Usage: $0 file.csv"; open CSV, $file or die $!; my @csv_content = <CSV>; close CSV; my $dbname = "dabasename"; my $dbhost = "localhost"; my $dbport = "3306"; my $dbuser = "username"; my $dbpass = "passwod"; my $table = "tablename"; my $dsn = "dbi:mysql:dbname=$dbname;host=$dbhost;port=$dbport;"; my $dbh = DBI->connect($dsn, $dbuser, $dbpass) or die "Connection erro +r: $DBI::errstr"; my $sth; my $statement; my $field_line = shift(@csv_content); chomp($field_line); my @values; my $status; my $line; my $csv = Text::CSV->new(); foreach(@csv_content){ if($csv->parse($_)){ @values = $csv->fields(); $status = $csv->combine(@values); $line = $csv->string(); $statement = "INSERT INTO $table($field_line) VALUES($line);"; print $statement."\n"; $sth = $dbh->prepare( $statement ); $sth->execute() or die "$! $DBI::errstr"; } }

In reply to Load CSV file into Database by fauria

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.