tags:

views:

79

answers:

1

I am trying to implement sql LIKE qualifier with placeholders for a set of values. I know how to do it for one particular value as follows:

use strict;
use DBI;
my $dbh = DBI->connect("dbi:Sybase:server=$Srv;database=$Db", "$user", "$passwd") or die "could not connect to database";
my $query = "Select key, first_name from names where last_name like ? ";
my $sth = $dbh->prepare( $query ) or die "could not prepare statement\n", $dbh->errstr;
$sth->bind_param(1, "Mar%") or die "Could not bind_param", $sth->errstr ;
$sth->execute or die "Could not execute $query", $sth->errstr;
while (my @result = $sth->fetchrow_array){
print "@result\n";
}

When I try to make changes so as to implement the above code for a set of values present in array @l_names, I don't get any result. I am doing it as follows:

use strict;
use DBI;
open (FH, "/home/usr/file") or die $!;
my @l_names= <FH>; 
close(FH);

my $dbh = DBI->connect("dbi:Sybase:server=$Srv;database=$Db", "$user", "$passwd") or die "could not connect to database";
my $query = "Select key, first_name from names where last_name like ? ";
my $sth = $dbh->prepare( $query ) or die "could not prepare statement\n", $dbh->errstr;
foreach my $l_name (@l_names){
    $sth->bind_param(1, "$l_name%") or die "Could not bind_param", $sth->errstr ;
    $sth->execute or die "Could not execute $query", $sth->errstr;
}
while (my @result = $sth->fetchrow_array){
    print "@result\n";
}

Any suggestions on what is going wrong and how to correct it? Thanks!

+4  A: 

You didn't remove EOL marker from lines you'lve read from file. Here is fix for it:

my @l_names = <FH>; 
chomp(@l_names);

Update:

You can also look at "How can I select multiple rows using parameters from an array in Perl’s DBI module?" question

Ivan Nevostruev
or in one line: chomp(my @l_names = <FH>);
runrig