如何使用perl将数据库的每一行保存为目录中的单独数据块文件?

时间:2012-06-18 18:46:48

标签: database arrays perl hash

现在,我有一个包含大约20列和70行的数据库。我想迭代每一行并将每一行保存为一个单独的数据块,文件名由前三列生成。我已经有SQL代码选择我想要的特定列,并根据我想要的参数进行排序。我想要文件的目录在c:/database/first_past

在我的代码中,$ds是一个哈希数组的变量,即我当前的数据库。我有两个for循环遍历数据库并进入行,但是我不确定要插入的行以将该行保存为上面提到的具有特定标题参数的单独文件。

这在Perl中是否可行?以下是我目前使用的部分代码:

for my $rec (@{$ds->{DATA}}) {
    for my $role (keys %{$rec} } {
        #here is the save file line? ("$role=$rec->{$role}"
    }
}

$ds是一个哈希数组,DATA字段是一行的所有数据。

1 个答案:

答案 0 :(得分:3)

use DBI qw( );

my $dbh = DBI->connect($dsn, $user, $passwd, {
   RaiseError       => 1,
   PrintError       => 0,
   PrintWarn        => 1,
   AutoCommit       => 1,
   FetchHashKeyName => 'NAME_lc',
});

my $sth = $dbh->prepare('
    SELECT *
      FROM Table
     ORDER BY ...
');

$sth->execute();
while (my $row = $sth->fetch()) {
    my $fn = join('-', @{$row}[0,1,2]);
    my $qfn = "c:\\database\\first_past\\" . $fn;
    open(my $fh, '>', $qfn) or die $!;
    print($fh ...);
}

DBIopenprint


您的后续问题:

$sth->execute();
while (my $row = $sth->fetch()) {
    my $fn = join('-', @{$row}[0,1,2]);
    my $qfn = "c:\\database\\first_past\\" . $fn;
    open(my $fh, '>>', $qfn) or die $!;
    print($fh ...);
}

my $last_fn;
my $fh;
$sth->execute();
while (my $row = $sth->fetch()) {
    my $fn = join('-', @{$row}[0,1,2]);
    if (!defined($last_fn) || $last_fn ne $fn) {
        $last_fn = $fn;
        my $qfn = "c:\\database\\first_past\\" . $fn;
        open($fh, '>', $qfn) or die $!;
    }

    print($fh ...);
}