Using Perl ? bind inside single quotes

安稳与你 提交于 2019-12-11 18:35:06

问题


This scripts works fine for all commands that don't require % wildcards. When I attempt to wrap the ? in %?% which producing a bind error. Also I have tried adding %value% to the argument when running the script and it also producing the same error. Is there a way to substitue an argument into a SQL DBI command in perl?

Thanks, in advance.

#!/usr/bin/perl

use DBI;
use Text::Diff;
use File::stat;
use Fcntl ':flock';

open (LOCK_FH, $0) || die "$0 for lock: $!\n";
flock (LOCK_FH, LOCK_EX|LOCK_NB) || die "$0 already running\n";

$BINDVAR = $ARGV[0];
$dbname = "COnnectionDetailsHere";
$un = "username";
$pw = "password";

my $dbh = DBI->connect ( $dbname, $un, $pw, { PrintError=>1, RaiseError=>1, AutoCommit=>0, LongReadLen=>5056}) or die "Couldn't connect to DB: " . DBI->errstr;

$sql = <<SQL

select * from foo where bar like '%?%' '?'

SQL
;

$stm = $dbh->prepare($sql) or die "SQL failed to prepare $DBI::errstr\n";

$stm->bind_param(1,($BINDVAR));

$stm->execute() or die "Couldn't execute the statement: " . $stm->errstr;

回答1:


Put the % into the variable and don't put quotes around the ?. That's what's screwing you up - the quotes turn it into a literal question mark.

#!/usr/bin/env perl    

use strict;
use warnings;

use DBI;

my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:');
$dbh->do('CREATE TABLE foo ( bar text )');
$dbh->do(q(INSERT INTO foo VALUES ('xyzzy')));

my $sth = $dbh->prepare('SELECT * FROM foo WHERE bar LIKE ?');
$sth->execute('%');

print $sth->fetchrow_array . "\n";

Output:

$ ~/src/tmp/like_qry 
xyzzy



回答2:


It's not adding the % that cause the problem, it's adding the quotes. ? is a placeholder. '?' is a string literal that evaluates to a question mark.

The previous answer effectively suggested you move the concatenation to the Perl side.

my $sth = $dbh->prepare('SELECT * FROM foo WHERE bar LIKE ?');
$sth->execute('%' . $something . '%');

You can keep doing it in the server by using the correct syntax.

my $sth = $dbh->prepare(q{SELECT * FROM foo WHERE bar LIKE '%' || ? || '%'});
$sth->execute($something);

but there's no benefit of that and it risks using incompatible syntax.



来源:https://stackoverflow.com/questions/12773109/using-perl-bind-inside-single-quotes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!