Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/perl -w
- use strict;
- use DBI;
- use Text::CSV_XS;
- use Getopt::Long;
- use constant USAGE => "usage: $0 [ -h hostname ] [ -o port ] --db dbname -u user -p passwd -t table file.csv [ file.csv ... ]";
- GetOptions(
- 'h|host=s' => \( my $opt_host = "stncss00.tnc" ),
- 'o|port=i' => \( my $opt_port = "3306" ),
- 'db=s' => \( my $opt_dbname ),
- 'u|user=s' => \( my $opt_user ),
- 'p|pass=s' => \( my $opt_pass ),
- 't|table=s' => \( my $opt_table ),
- ) or die USAGE;
- #die USAGE
- # if not( $opt_dbname and $opt_user and $opt_pass and $opt_table );
- $opt_table='test';
- my $csv = Text::CSV_XS->new(); #auto_diag =>1
- my $firstline=<>;
- print "$firstline\n";
- $csv->parse( $firstline ); # first line
- my @field = $csv->fields();
- print join(', ',@field),"\n";
- my $sql =
- "INSERT INTO $opt_table ("
- . join( ',', @field )
- . ") VALUES ("
- . join( ',', ( '?' ) x @field )
- . ")";
- print STDERR "Using query: $sql\n";
- exit;
- my $dbh = DBI->connect(
- "dbi:mysql:dbname=$opt_dbname;host=$opt_host;port=$opt_port",
- $opt_user,
- $opt_pass,
- { RaiseError => 1, PrintError => 0 }
- ) or die "Connection error: $DBI::errstr";
- my $sth =$dbh->prepare( $sql );
- my ( $buff, $lnr );
- while( <> ) {
- $buff .= $_;
- if( $csv->parse( $buff ) ) {
- $sth->execute( $csv->fields );
- $buff = '';
- $lnr = $. + 1;
- }
- }
- perl a.pl <a.csv
- Print objekt,Press edition,Product typ,Issue reference,Line,Run ID,Title,Edition,Planned start,Plann
- ed end,Start time,End time,Gross utr,Stack utr,Wound utr,Overflow utr,Unwound hutr,MSD ep,Stack hutr
- ,Wound hutr,Overflow hutr,fat,skew
- Print objekt, Press edition, Product typ, Issue reference, Line, Run ID, Title, Edition, Planned sta
- rt, Planned end, Start time, End time, Gross utr, Stack utr, Wound utr, Overflow utr, Unwound hutr,
- MSD ep, Stack hutr, Wound hutr, Overflow hutr, fat, skew
- Using query: INSERT INTO test (Print objekt,Press edition,Product typ,Issue reference,Line,Run ID,Ti
- tle,Edition,Planned start,Planned end,Start time,End time,Gross utr,Stack utr,Wound utr,Overflow utr
- ,Unwound hutr,MSD ep,Stack hutr,Wound hutr,Overflow hutr,fat,skew) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?
- ,?,?,?,?,?,?,?,?,?,?)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement