Saturday, October 21, 2006

How to do a "fuzzy" MySQL query using Perl DBI

Suppose you have a MySQL query as follows:
SELECT last_name FROM customers WHERE last_name LIKE "%smith%"
and you want to use the Perl DBI prepared statement API to query your database. This is how you code it:

#!/usr/bin/perl

use strict;
use warnings;
use DBI;

my $dbname='your_database_name';
my $dbh = DBI->connect("dbi:mysql:dbname=$dbname;host=localhost");
my $sth = $dbh->prepare("SELECT last_name FROM customers WHERE last_name LIKE ? ");
my $name = "%smith%";
$sth->execute($name);
while ( my @row = $sth->fetchrow_array ) {
   print "Row @row\n";
}


I was briefly befuddled in trying to put the percent characters in the SQL query itself, along with the placeholder, which does not work.

The DBI section on placeholders does give you a hint about how to handle this case. You just need to read the page carefully!

0 Comments:

Post a Comment

<< Home