mysql,perl,从mysql表下载csv

时间:2011-11-17 23:25:12

标签: mysql perl

我在perl中有这个脚本,它崩溃了。该数据库可能是百万行。我怎样才能做到这一点?感谢

sub MYSQL_CREATE_CSV
{
    my ($dbh, $tablename, $csvname) = @_;
    my $mysql_tablename = $dbh->quote_identifier($tablename);

    print "[INFO] EXTRACTING INFO FROM TABLE : $mysql_tablename\n";
    my $sth1 = $dbh->prepare(qq|SELECT * FROM $mysql_tablename | );
    $sth1->execute(  );

    open (FILE, ">$csvname") or die "[ERROR] $0 - cannot write to file : $! \n";
    #   EXTRACT COLUMN NAME
    my @COLUMNNAME = @{$sth1->{NAME}};
    my $temp = join (",",@COLUMNNAME);
    print FILE $temp , "\n";
    while ( my @row = $sth1->fetchrow_array(  ) )
    {
        my $temp = join(",",@row);
        print FILE $temp . "\n";
    }
    close FILE;

    print "[INFO] \t\tCREATING FILE : $csvname \n" if (-e $csvname);
}

2 个答案:

答案 0 :(得分:2)

$dbh->prepare()

之前尝试这一行
$dbh->{'mysql_use_result'} = 1;

这将告诉MySQL不要将整个结果加载到内存中。

答案 1 :(得分:1)

跳过所有perl并直接转储它:

SELECT * FROM my_table INTO OUTFILE 'file.csv' FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'; 

它不会包含列名称,但您可以调整查询以添加它们。