On 01/28/2005 03:55 AM, Ing. Branislav Gerzo said:

Hi all!

I have subroutine, that checks, if I already have in DB specified row:

sub image_exist {
  my ($id, $date) = @_;          #id is _always_ number
  my $sth = $mydbh->prepare_cached("select ID from pic where id = ?");
  $sth->execute($id);
  my $rows = $sth->fetchall_arrayref();
  if ( @$rows[0] ) {
          print "$id exist\n";
  } else {
          print "$id not exist\n";
  }
}

I am pretty sure, this can be done better. Also I am curious about
this - when I change statement to:
my $sth = $mydbh->prepare_cached("select ID from pic where id = $id");
$sth->execute();

In addition to Thilo's suggestions, if you are calling this routine often, you can prepare once and execute many times.


   my image_exist_sth;
   sub image_exist {
      if ( ! $image_exist_sth ) {
         my $sql = "select ID from pic where id = ?";
         $image_exist_sth = $mydbh -> prepare( $sql )
            or die "Can't prepare '$sql', $DBI::errstr\n";
      }
      my ( new_id ) = $mydbh -> selectrow_array( $image_exist_sth,
         {}, $id ) or die "Can't check for image, $DBI::errstr\n";
      print( defined $new_id
         ? "$id exists\n" : "$id does not exist\n" );
   }

--
Mac :})
** I usually forward private questions to the appropriate mail list. **
Ask Smarter: http://www.catb.org/~esr/faqs/smart-questions.html
Give a hobbit a fish and he eats fish for a day.
Give a hobbit a ring and he eats fish for an age.

Reply via email to