【问题标题】:perl, dbi with sql statement with a like conditionperl, dbi with sql statement with a like condition
【发布时间】:2010-07-21 13:57:33
【问题描述】:

在我的代码中,我必须使用类似条件进行简单的 sql 查询。 我就是这样做的

my $out = "/Users/zero/out.log";
my $filename = "/Users/zero/data.txt";


my $dbh = DBI->connect("DBI:Oracle:sid=$sid;host=$host;port=$port", $user, $pwd) or die "Couldn't connect to database: " . DBI->errstr;
my $query = "select SOMETHING from SOMETHING_1 where SOMETHING like ?||'%' ";
my $sth = $dbh->prepare($query) or die "Connection Error: " . $dbh->errstr;
open (IN,"< $filename") or die("Unable to open $filename");        
my @righe = <IN>;
close IN;
open (OUT,">$out") or die "Unable to open $out";
foreach my $riga (@righe) {
        chomp $riga;
        (my $valore) = split (/\n/, $riga);
        $sth->execute($valore) ||print "Impossibile eseguire la query $query";
        while (my $real = $sth->fetchrow_array) {
                       print OUT "\"$real\"\n";
                    }
    }
$sth->finish;
$dbh->disconnect();

但查询返回所有行,忽略类似条件。 我的错在哪里?

谢谢

【问题讨论】:

  • 不相关但使用词法文件句柄和 3 个文件打开。例如打开(我的 $in, 'perldoc.perl.org/functions/open.html
  • 哦,我还建议打破长行和更多的空白。

标签: sql perl dbi sql-like


【解决方案1】:

您必须将 % 字符连接到您搜索的变量。

my $query = "select SOMETHING from SOMETHING_1 where SOMETHING like ?";
...
$sth->execute($valore.'%') ||print "Impossibile eseguire la query $query";

【讨论】:

  • 好的,我现在试试。我尝试连接“%”,但在我的 $query 中。
  • 您不能在查询中使用% 字符,因为您使用的是? 占位符,它会自动引用您的$valore 变量(这是一件好事)。这意味着在 query 中使用 % 会导致字符串看起来像 "somevalue"% 而它需要看起来像 "somevalue%"
  • @Jonas 这真的很有帮助,因为直到现在我都不得不面对同样的问题。干杯。
猜你喜欢
  • 1970-01-01
  • 2022-12-02
  • 1970-01-01
  • 2019-12-01
  • 2016-06-04
  • 2022-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多