使用Perl DBI获取所有记录
发布时间:2020-12-16 06:09:20 所属栏目:大数据 来源:网络整理
导读:我有一个使用 DBI连接的Perl脚本.我使用子例程打开并读取SQL脚本文件.我只打印一条记录,我应该再打印两条记录(总共三条记录).我如何获得所有记录? 结果: Alert:OUTBOUND_DATA:0 脚本: my $dbh_oracle = DBI-connect( $CFG{oracle_dbi_connect},$CFG{db_us
我有一个使用
DBI连接的Perl脚本.我使用子例程打开并读取SQL脚本文件.我只打印一条记录,我应该再打印两条记录(总共三条记录).我如何获得所有记录?
结果: Alert:OUTBOUND_DATA:0 脚本: my $dbh_oracle = DBI->connect( $CFG{oracle_dbi_connect},$CFG{db_user},$CFG{db_cred},{AutoCommit => 0,RaiseError => 0,PrintError => 0}) or die ("Cannot connect to the database: ".$DBI::errstr."n"); my ($val1,$val2) = get_data(); print "Alert:$val1:$val2n"; send_email("Alert:$val1:$val2"); sub get_data { undef $/; open (my $QFH,"< /sql/summary.sql") or die "error can't open this file $!"; my $sth= $dbh_oracle->prepare(<$QFH>) or die ("Cannot connect to the database: ".$DBI::errstr."n"); $sth->execute; close $QFH; my $row = $sth->fetchrow_hashref; $sth->finish; return @$row{'MYTABLE','FLAG'}; } sub send_email { my $message = shift; open (MAIL,"|/usr/sbin/sendmail -t") or die "Can't open sendmail: $!"; print MAIL "To: me@test.comn"; print MAIL "From: Datan"; print MAIL "n"; print MAIL $message; close MAIL; } exit; 运行查询的结果:(超过1 rec) MYTABLE FLAG ----------------------- ---------- OUTBOUND_DATA 0 MSGS_BY_DIM 0 INBOUND_DATA 0 3 rows selected. 解决方法
它还取决于您构建整个脚本的方式.您的get_data()调用仅允许返回一对值.我看到至少有两个选项:要么返回包含所有数据的哈希(引用)并让main组装它,要么使用前面提到的循环结构并在子例程中构造消息体,只返回一个标量字符串.
要将所有数据作为哈希引用返回,get_data子例程可能如下所示(注意我使用fetchall_hashref而不是fetchrow_hashref: sub get_data { undef $/; open (my $QFH,"< /sql/summary.sql") or die "error can't open this file $!"; my $sth= $dbh_oracle->prepare(<$QFH>) or die ("Cannot connect to the database: ".$DBI::errstr."n"); $sth->execute; close $QFH; my $hash_ref = $sth->fetchall_hashref('MYTABLE'); $sth->finish; return $hash_ref; } 你从main调用它并使用输出如下: my $hash_ref = get_data(); my $message = ""; foreach my $table (sort keys %$hash_ref) { $message .= join(":","Alert",$table,$$hash_ref{$table}{'FLAG'}) . "n"; } 这将导致$message包含: Alert:INBOUND_DATA:0 Alert:MSGS_BY_DIM:0 Alert:OUTBOUND_DATA:0 你可能想要礼貌地: $dbh_oracle->disconnect; 在你退出之前. 这有一些问题,例如你已经在外部脚本中保存了SQL,但是我已经使用了硬编码密钥(MYTABLE,我认为在你的查询中是唯一的)和值(FLAG)脚本,当你想要扩展它时,这将限制. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |