现在,我有一个包含大约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
字段是一行的所有数据。
答案 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 ...);
}
您的后续问题:
$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 ...);
}