#!/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"; } }
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Load CSV file into Database
by Aristotle (Chancellor) on Jan 31, 2005 at 07:01 UTC | |
by tilly (Archbishop) on Jan 31, 2005 at 09:26 UTC | |
by Aristotle (Chancellor) on Jan 31, 2005 at 10:12 UTC | |
by tilly (Archbishop) on Feb 01, 2005 at 00:53 UTC | |
by Aristotle (Chancellor) on Feb 01, 2005 at 04:49 UTC | |
by rdfield (Priest) on Jan 31, 2005 at 09:26 UTC | |
|
Re: Load CSV file into Database
by jZed (Prior) on Jan 31, 2005 at 20:15 UTC | |
|
Re: Load CSV file into Database
by bradcathey (Prior) on Jan 31, 2005 at 19:24 UTC |