将变量传递给perl中的sqlplus查询

时间:2012-10-22 01:41:25

标签: perl oracle

我在这里遇到问题。我试图将一个变量传递给一个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 个答案:

答案 0 :(得分:5)

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

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

应该是

where cycle=?       -- This is a placeholder

然后问题是您实际上没有为占位符传递值。

$query_handle->execute();

应该是

$query_handle->execute($cycle);

答案 1 :(得分: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);

如果您启用了代码,那么您所拥有的代码就会触发警告;确保你这样做,并且你弄清楚如何回应任何你得到的。

答案 2 :(得分: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,我想是这样的。

答案 3 :(得分: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';
  }