现在,我有一个包含大约 20 列和 70 行的数据库。我想遍历每一行并将每一行保存为一个单独的数据 block ,文件名由前三列生成。我已经有 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
字段是一行的所有数据。
最佳答案
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 ...);
}
关于database - 如何使用 perl 将数据库的每一行保存为目录中的单独数据 block 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11089098/