This script converts each table in each mySQL database found into a .csv-file.
#!/usr/bin/perl -w
#-----------------------------------------------------------------------------
#
# Name mySQL2csv.pl
#
# Description :
# Convert database tables to csv files
#
# Limitations:
# It doesn't look very efficient looping over a hash for each row
# usage:
# mySQL2csv.pl
#
#-----------------------------------------------------------------------------
##### Standard code, think twice before modifying. Modify template too. ###
use strict;
use DBI;
$0 =~ s:.*/::;
##### End of standard code, think twice before modifying. Modify template too. ###
#
# MAIN
#
my ($dsn, $dbh, $sth, $database, $table, $sql, $key, $hash_ref, $outline, $outfile);
my @databases = ();
my @tables = ();
my @fields = ();
my $serverName = "localhost";
my $serverPort = "3306";
my $serverUser = "root";
my $serverPass = "ThePassword";
@databases = DBI->data_sources("mysql", {"host" => $serverName, "port" => $serverPort, "user" => $serverUser, "password" => $serverPass});
foreach $dsn (@databases) {
print ("Database: $dsn \n");
# If you don't need all databases select what you do want to see
if ( $dsn =~ /pattern/ ) {
$dbh = DBI->connect($dsn, $serverUser, $serverPass) ||die "Unable to connect to database";
@tables = $dbh->tables();
foreach $table (@tables) {
$outfile = $table;
$outfile =~ s/\`//g;
$outfile =~ s/\./_/g;
$outfile .= ".csv";
open (OUTFILE, "> $outfile") || die("Open failed for $outfile");
print ("table: $table $outfile\n");
$sql = "select * from $table";
$sth = $dbh->prepare($sql);
$sth->execute;
@fields = @{$sth->{NAME}};
print OUTFILE join(",",@fields)."\n";
while ( $hash_ref = $sth->fetchrow_hashref() ) {
foreach $key (@fields) {
$outline .= $hash_ref->{$key}.",";
}
chop $outline;
print OUTFILE $outline."\n";
$outline = "";
}
close OUTFILE;
}
} # End of $dsn-selection
}
mySQL2csv.pl