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

标签 database arrays perl hash

现在,我有一个包含大约 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 ...);
}

DBI , open , print


对于您的后续问题:

$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/

相关文章:

java - Oracle - 可用数据在 SQL 命令行/Java 程序中不可见

perl - 判断你的 perl 是否在 -e 上运行的最好方法是什么?

android - 绿道。 N :M relation

python - SQLAlchemy 中关系的高效查询

python - 保证非零相等时的 Numpy 二维数组联合

c++ - 在数组中存储 200kb 的数据?

javascript - 需要通过坐标识别Img标签

python - 如何从 Python 读取 Perl 数据结构?

xml - 我如何轻松测试 XML 文件在 Perl 中的格式是否正确?

mysql - 将表与一对一关系组合起来