2015-09-07 24 views
-2

我有一個perl腳本,它以HTML格式從Oracle數據庫打印表格內容。如何在perl中有條件地發送電子郵件警報

我的腳本會每天的基礎上,這將不僅僅是電子郵件的簡單的SQL查詢的O/P上運行(選擇查詢)

現在我想我的腳本停止電子郵件警報每當表中的記錄數是NULL即表中沒有記錄。

這裏是我的部分腳本

$retCode = executeSQL("select firstname,lastname,employee_id from employee"); 

if ($retCode) { 
    push(@HTML, "<tr><td>&nbsp;</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 = '[email protected]'; 
    $to = '[email protected]'; 

    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"); 
    } 
} 
+2

...你的問題是什麼? – Sobrique

+0

當sql查詢沒有產生任何行時,我不應該觸發電子郵件。 – stephenjacob

+1

這是一個陳述,而不是一個問題。 :) – simbabque

回答

0

該解決方案已經存在的代碼。如果沒有從DB查詢返回的行,程序不會將錶行添加到電子郵件的HTML正文中。因此,您需要將發送命令轉換爲該條件。

if($retCode) { 
    push(@HTML,"<tr><td>&nbsp;</td><td></td><td>"); 
    push(@HTML,"<td></td><td></td></tr>\12"); 

    push(@HTML,"</table>\12\12"); 
    push(@HTML, "COUNT : $count\12"); 

    &sendMail; 
} 
0

我認爲這裏的大小姐是在executeSQL,你沒能有一個return條款說明您是否沒有找到任何查詢行結束。

if (executeSQL("select firstname,lastname,employee_id from employee")) 
{ 
    push(@HTML, "<tr><td>&nbsp;</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 
} 

這就是說,有一些其他的改進空間,其中一些已經提到:

  1. 考慮通過一個參考@HTML,而不是使用它作爲一個全球性的 - 鬆耦合
  2. 可能應該關閉你的SQL - 我加了$sth->finish$dbh->disconnect作爲例子
  3. 你看了一下HTML :: Table嗎?我使用它很多,這是一個真正的節省時間。動態創建HTML對我來說永遠是最後一招
相關問題