0

我这里有问题。我正在尝试将变量传递给 sqlplus 查询,但它似乎不起作用。

    my $connect = DBI->connect('DBI:Oracle:',$dbuser,$dbpasswd);
  my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle='?'", $cycle;
  my $query_handle = $connect->prepare($query);
  $query_handle->execute();
  $cmte_money = $query_handle->fetchrow_array();

  print 'Money: ';
  print $cmte_money;

  if($cmte_money > 0)
  {
    print 'HI';
  }
  else
  {
    print 'NOOOO';
  }

当我将“cycles”变量从变量更改为常量时,我​​可以让查询工作,并且 if 语句检查将打印 hi,所以数据库工作我很肯定。

我搜索了互联网,我似乎无法找到答案。

4

4 回答 4

5

首先,您的意思是使用占位符,但您没有。

where cycle='?'     -- This is a string

应该

where cycle=?       -- This is a placeholder

还有一个问题是你实际上并没有为占位符传递一个值。

$query_handle->execute();

应该

$query_handle->execute($cycle);
于 2012-10-22T01:51:23.257 回答
1

占位符的替换被传递执行,所以:

my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle=?";
my $query_handle = $connect->prepare($query);
$query_handle->execute($cycle);

如果您启用它们,您拥有的代码会触发警告;确保你这样做,并且你弄清楚如何回应你得到的任何东西。

于 2012-10-22T01:43:43.713 回答
0

这是一个例子:

use strict;

    use DBI;

    my $connect = DBI->connect('DBI:Oracle:', $dbuser, $dbpasswd); 
    my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle = `$cycle`"; 
    my $query_handle = $connect->prepare($query); 
    $query_handle->execute(); 
    @cmte_money = $query_handle->fetchrow_array(); 

    print 'Money: '; 
    print @cmte_money; 

    if($#cmte_money >= 0) 
    { 
      print 'HI'; 
    } 
    else 
    { 
      print 'NOOOO'; 
    } 

我定义了一个常量变量$cycle,我是这样想的。

于 2012-10-22T06:39:48.487 回答
0
  my $connect = DBI->connect('DBI:Oracle:',$dbuser,$dbpasswd);
  # Tell the DBI that the query uses bind variable with ? (question mark)
  my $query = "select sum(transaction_amnt) from comm_to_cand natural join cmte_id_to_geo where cycle=?";
  my $query_handle = $connect->prepare($query);
  # Pass the value 
  $query_handle->execute($cycle); # assuming the variable is defined (otherwise it will pass as NULL into the query)
  $cmte_money = $query_handle->fetchrow_array();

  print 'Money: ';
  print $cmte_money;

  if($cmte_money > 0)
  {
    print 'HI';
  }
  else
  {
    print 'NOOOO';
  }
于 2016-10-29T00:33:07.157 回答