JaeDre619 has asked for the wisdom of the Perl Monks concerning the following question:

Dear Monks, as a perl novice I am always looking at best practices to handling/setting up efficient processing. I have got some working code, but I want to add another feature as well as improve this code. After some testing, I know this needs a lot of improvement. I am hoping to get some good tips and would like your help in adding this functionality and make the existing code better. Thank you.

Here's a summary of what it does now:

  1. open a dbh and run query1.sql
  2. query1.sql should return a value of 1 or 0 (my flags)
  3. if flag=0 (pass)
  4. if flag=1 (fail), print mesg send it in email

Here's what I want to add:

  1. if flag=1 (fails), then run query2.sql
  2. query2.sql will have (2) cols of info I need
  3. add the contents of query2.sql to body of my email and its output too
  4. if dbi handle errors, also add error to the email body as a mesg

I also want to handle the (2) output values for other customized print statements

How do I add, make it flexible to kick off query2.sql? Also, how do I make fetchrow_hashref handle the option of either 1 or 2 col values returned?

my $dbh = DBI->connect( $info{dsn}, $info{db_user}, $info{db_cred}, {AutoCommit => 0, RaiseError => 0, PrintError => 0 }) || die ("Cannot connect: ".$DBI::errstr."\n" +); my $flg = get_flg(); $dbh->disconnect(); # Check flg if ($flg == 0 ) { send_email("PASS:$flg\n"); } elsif ($flg == 1) { #Call to query2.sql here send_email("FAIL:$flg\n"); exit; }; $dbh->disconnect; sub get_flg { undef $/; open (my $fh, "< query1.sql") or die "error opening this file $!"; my $sth= $dbh->prepare(<$fh>) || die ("Cannot connect: ".$DBI::errstr."\n"); $sth->execute; close $fh; my $row = $sth->fetchrow_hashref; $sth->finish; return $row->{VAL1}; print $row; } sub send_email { my $message = shift; open (MAIL, "|/usr/sbin/sendmail -t") or die "Error opening sendma +il: $!"; print MAIL "To: me\@myhost.com\n"; print MAIL "From: checks"; print MAIL "Subject: Status Checks\n"; print MAIL "\n"; print MAIL $message; close MAIL; }
  • Comment on Code improvement setting up multiple dbi calls based on a condition
  • Download Code

Replies are listed 'Best First'.
Re: Code improvement setting up multiple dbi calls based on a condition
by JavaFan (Canon) on Jul 22, 2011 at 00:50 UTC
    How do I add, make it flexible to kick off query2.sql?
    Your code shows that you've already mastered querying the database and retrieving data; it also shows you know about the if statement.

    So, I'm wondering, why are you asking this question?

Re: Code improvement setting up multiple dbi calls based on a condition
by mje (Curate) on Jul 22, 2011 at 08:06 UTC