2

我有一个 Perl DBI 语句

my $sql_statement = "select c.* ".
                    "from meter_category c ".
                    "where c.category = ".$current_category." ".
                    "and c.effective_date <= ".
                    $DBHdl->quote($time_stamp)." ".
                    "and c.meter_size = ".$meter_size." ".
                    "order by c.effective_date desc ; ";

$DBHdl是一个 Informix 数据库句柄。

该声明如下所示:

select c.* 
from meter_category c 
where c.category = 1 
and c.effective_date <= '09/20/2013'
and c.meter_size = 0.63 
order by c.effective_date desc ;

在我的函数中,我想设置$current_category为 2,然后修改 $sql_statement。

$current_category = 2;
eval $sql_statement

不会改变 $sql_statement,所以c.category = 2.

有没有办法执行替换,还是我必须重新发出声明?

我使用以下代码为 $current_category 的每个值准备和执行查询。

my $ptSelHdl = $DBHdl->prepare($sql_statement);

die("Could not prepare \$sql_statement for meter charge.\n")
 if(!$ptSelHdl || !$ptSelHdl->execute);
4

1 回答 1

10

使用占位符?以下语句中的 s)指示执行语句时将提供的值:

my $sql_statement = "select c.* ".
                    "from meter_category c ".
                    "where c.category = ? ".
                    "and c.effective_date <= ?".
                    "and c.meter_size = ? ".
                    "order by c.effective_date desc ; ";

my $sth = $DBHdl->prepare($sql_statement)
    or die "Could not prepare \$sql_statement for meter charge: " . $dbh->errstr;

$sth->execute($current_category, $time_stamp, $meter_size)
    or die "Could not execute \$sql_statement for meter charge: " . $dbh->errstr;

然后您可以使用不同的参数多次执行它,例如:

# Modify $current_category and re-execute
$current_category = 2;
$sth->execute($current_category, $time_stamp, $meter_size)
    or die "Could not execute \$sql_statement for meter charge: " . $dbh->errstr;

使用占位符是一种很好的做法,因为如果您的任何变量来自不受信任的来源,它们还将保护您免受SQL 注入攻击。

于 2013-09-20T15:33:45.513 回答