SQL LIKE with% query for text in Perl

I have the following piece of code:

$query = "SELECT tac FROM lte_modems WHERE tac = ?";
$check_name = $dbh->prepare($query);
$my_name = "Jo"         
$check_name->execute($my_name);
my @result = $check_name->fetchrow_array();

      

which works great. I would like to modify the SQL query to return names starting with "Jo": i.e. my SQL query should be

   $query = "SELECT tac FROM lte_modems WHERE tac LIKE '?%'";

      

but it doesn't work. any help pls? maybe i need to escape some characters?

early

+3


source to share


2 answers


You need to include %

in your parameter. Otherwise, you will get extra quotes as DBI descriptors for you.

my $sth = $dbh->prepare( "SELECT tac FROM lte_modems WHERE tac LIKE ?" );
$sth->execute( $my_name . '%' );

      



The trick really always allows DBI to do all the quotes and do nothing by itself. DBI doesn't care if the placeholder comes ?

after the equals =

, a LIKE

or REGEXP

or whatever. This speeds up quotes and adds quotes as needed. You don't want to get involved in this.

+7


source


You specified ?

by turning it from placeholder to string. Use

my $sth = $dbh->prepare("SELECT tac FROM lte_modems WHERE tac LIKE ?");
$sth->execute($my_name . '%');

      



or

my $sth = $dbh->prepare("SELECT tac FROM lte_modems WHERE tac LIKE CONCAT(?, '%')");

      

+1


source







All Articles