Below is the script to extract a table from the mysql database to a flat file.
You need to change the DB_NAME, USERNAME and PASSWORD.
##### Start Script #############
#!/usr/bin/perl -w
use strict;
use DBI;
use DBD::mysql;
my ($dbh, $sql, $sth, $re, $header, $table);
if ($#ARGV ne 0)
{
print "Usage: $0 < TABLE_NAME>\n";
exit;
}
$table=$ARGV[0];
$dbh=DBI->connect('dbi:mysql:DB_NAME','USERNAME','PASSWORD',{AutoCommit => 0, RaiseError => 1}) or die "Unable to connect to DB_NAME: $dbh->err\n";
$sql=<<_KAL_;
select * from $table
_KAL_
$sth = $dbh->prepare($sql) or die "Unable to prepare $sql\n";
$sth->execute();
open(KAL, ">$table.dat") or die "Unable to open $table.dat for writing\n";
$header=$sth->{NAME};
print KAL join('|', @$header), "|\n";
while($re=$sth->fetchrow_arrayref())
{
print KAL join('|', @$re), "|\n";
}
close(KAL);
$sth->finish;
$dbh->disconnect;
##### End Script #############
How to run
copy the contents from start script to end script and place in a file named extract.pl
$ chmod a+x extract.pl
$ ./extract.pl emp
$ more emp.dat