Skip to content

Instantly share code, notes, and snippets.

@sycobuny
Created July 24, 2014 21:52
Show Gist options
  • Save sycobuny/6859644035647f9a5636 to your computer and use it in GitHub Desktop.
Save sycobuny/6859644035647f9a5636 to your computer and use it in GitHub Desktop.
# we assume $dbh gets assigned somewhere else
sub do_query {
my ($name, $wildcard) = @_;
my ($sth) = $dbh->prepare(<<<QUERY);
SELECT *
FROM some_table
WHERE name = ? AND
address LIKE CONCAT('%', ?, '%');
QUERY
my ($res) = $sth->execute($name, $wildcard);
# do stuff...
$sth->free;
}
# we assume $dbh gets assigned somewhere else
sub_do_query: {
my ($sth) = $dbh->prepare(<<<' QUERY');
SELECT *
FROM some_table
WHERE name = ? AND
address LIKE CONCAT('%', ?, '%');
QUERY
sub do_query {
my ($name, $wildcard, $res) = @_;
$res = $sth->execute($name, $wildcard);
# do stuff...
}
}

It's been a while since I've used DBI, and I didn't bother with the docs, so some sub names (such as $dbh->execute()) or arguments (such as $dbh->prepare()) may be wrong, but the general gist is there.

Another potential way to crack the nut, if you're not making too many queries and/or you're using this one particular query a bunch, is to prepare the statement once, à la bind_2.pl, and then ever free() it, which means the legwork of parsing the SQL is already done, and you can just stick in some new parameters as necessary, and not necessarily have to worry about quoting them.

# we assume $dbh gets assigned somewhere else
sub do_query {
my ($name, $wildcard) = @_;
$name = $dbh->quote($name);
$wildcard = '%' . $dbh->quote($wildcard) . '%';
my ($res) = $dbh->execute(<<<QUERY);
SELECT *
FROM some_table
WHERE name = '$name' AND
address LIKE '$wildcard';
QUERY
# do stuff...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment