你跟「perl的」太標記這文件,所以這裏是一個Perl的解決方案。 「BETWEEN」子句是一次只能處理大量數據的簡單方法,因爲selectall_arrayref調用將(在當前版本的DBI模塊下)將您要求的所有數據加載到內存中。
mysql> insert into mail_attachs values (1, 'abc'), (2, 'def');
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
$ cat extract.pl
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my $output_dir = '/home/jmccarthy/mail_attachs';
my $dbh = DBI->connect_cached("DBI:mysql:database=test;host=dbmachine",
'username', 'password');
die "cannot connect, $DBI::err" if ! $dbh;
my $rows = $dbh->selectall_arrayref("SELECT attachid, filecontent FROM mail_attachs
WHERE attachid BETWEEN ? AND ?",
{ Slice => {} }, # get back better-self-documenting hashrefs, instead of arrayrefs
1, 1000); # values for the ?'s above
die "selectall_arrayref failed, $DBI::err" if $DBI::err;
for my $row (@$rows) {
open my $fh, '>', "$output_dir/file$row->{attachid}"
or die "cannot write $row->{attachid}, $!";
print $fh $row->{filecontent}
or die "cannot print to $row->{attachid}, $!";
close $fh
or die "cannot close $row->{attachid}, $!";
print "wrote $row->{attachid}\n";
}
$ ./extract.pl
wrote 1
wrote 2
$ head mail_attachs/file*
==> mail_attachs/file1 <==
abc
==> mail_attachs/file2 <==
def