我有一个perl脚本,它以HTML格式从Oracle DB打印表格内容。
我的脚本将每天运行,只会通过电子邮件发送简单的SQL查询的o / p(选择查询)
现在我希望我的脚本在表的记录数为NULL时停止电子邮件警报,即表中没有记录。
这是我的部分脚本
$retCode = executeSQL("select firstname,lastname,employee_id from employee");
if ($retCode) {
push(@HTML, "<tr><td> </td><td></td><td>");
push(@HTML, "<td></td><td></td></tr>\12");
}
push(@HTML, "</table>\12\12");
push(@HTML, "COUNT : $count\12");
&sendMail;
sub sendMail {
$sub = "sample data";
$from = 'xyz@abc.com';
$to = 'xys@abc.com';
open(MAIL, "|/usr/lib/sendmail -t");
print MAIL "From: $from \12"; print MAIL "To: $to \12";print MAIL "Cc: $Cc \12";
print MAIL "Subject: $sub \12";
print MAIL "Content-Type: text/html \12";
print MAIL "Content-Disposition:inline \12";
print MAIL @HTML;
close(MAIL);
}
sub executeSQL {
my $SQL = $_[0];
chomp($SQL);
print "$SQL\12";
my $hostname = $ENV{"ORACLE_DB"};
my $dbh = CommonFunctions::connect_DBI( $hostname, "USERNAME", "PASSWORD" )|| die "ERROR : Unable to connect to $hostname: $DBI::errstr\n\n";
my $sth = $dbh->prepare($SQL);
$sth->execute or die "EXEC ERROR $sth->errstr";
$count = 0;
while (@ary = $sth->fetchrow_array) {
$count++;
push(@HTML, "<tr>");
foreach(@ary) {
chomp($_);
push(@HTML, "<td>$_</td>");
print "$_,";
}
push(@HTML, "</tr>\12");
}
}
答案 0 :(得分:0)
解决方案已经存在于代码中。如果没有从数据库查询返回的行,则程序不会将表行添加到电子邮件的HTML正文中。因此,您需要将send命令移动到该条件中。
if($retCode) {
push(@HTML,"<tr><td> </td><td></td><td>");
push(@HTML,"<td></td><td></td></tr>\12");
push(@HTML,"</table>\12\12");
push(@HTML, "COUNT : $count\12");
&sendMail;
}
答案 1 :(得分:0)
我认为这里的重大错误是在executeSQL
的末尾,你没有return
子句,表明你是否在查询中找到了任何行。
if (executeSQL("select firstname,lastname,employee_id from employee"))
{
push(@HTML, "<tr><td> </td><td></td><td>");
push(@HTML, "<td></td><td></td></tr>\12");
push(@HTML, "</table>\12\12");
push(@HTML, "COUNT : $count\12");
&sendMail;
}
sub sendMail {
# no changes
}
sub executeSQL {
my $SQL = shift;
print "$SQL\12";
my $hostname = $ENV{"ORACLE_DB"};
my $dbh = CommonFunctions::connect_DBI( $hostname, "USERNAME", "PASSWORD" ) ||
die "ERROR : Unable to connect to $hostname: $DBI::errstr\n\n";
my $sth = $dbh->prepare($SQL);
$sth->execute or die "EXEC ERROR $sth->errstr";
my $count = 0;
while (@ary = $sth->fetchrow_array) {
# no changes
}
$sth->finish;
$dbh->disconnect;
return $count; # this is what I think you're missing
}
尽管如此,还有其他一些改进空间,其中一些已被提及:
$sth->finish
和$dbh->disconnect
作为示例