I have a Perl script that uses a DBI connection. I open and read the SQL script file using a sub routine. I am printing only one record, where I should have two more (three records total). How do I get all the records?
Result:
Alert:OUTBOUND_DATA:0
Script:
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:$val2\n";
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.com\n";
print MAIL "From: Data\n";
print MAIL "\n";
print MAIL $message;
close MAIL;
}
exit;
RESULTS from running query: (more than 1 rec)
MYTABLE FLAG
----------------------- ----------
OUTBOUND_DATA 0
MSGS_BY_DIM 0
INBOUND_DATA 0
3 rows selected.
It also depends on how you are structuring your overall script. Your
get_data()call only allows a single pair of values to be returned. I see at least a couple options: either return a hash (reference) containing all the data and let themainassemble it, or use the loop constructs mentioned previously and fabricate the message body inside the subroutine, returning only a single scalar string.To return all the data as a hash reference, the
get_datasubroutine might look like this (note I’m usingfetchall_hashrefinstead offetchrow_hashref:And you call it from
mainand use the output as follows:This will result in
$messagecontaining:And you may want to politely:
before you exit.
This has some problems, for example you’ve got the SQL stashed in an external script, but I have resorted to hard-coding the key (MYTABLE, which I am presuming is unique in your query) and the value (FLAG) in the script, which will be limiting later when you want to expand on this.