Perl中的Mysql查询参数问题

时间:2010-06-28 05:17:12

标签: mysql perl

我的代码有点问题,如果我手动输入值,查询工作正常。但如果我使用我的变量则失败。代码如下所示

my $get_meter_id = $dbh->prepare("SELECT * from t_readings where meter_serial = '21001652' AND ...");
$get_meter_id->execute() or die "Couldn't execute statement: ".$get_meter_id->errstr;
my $meter_reg_id = $get_meter_id->fetchrow_array();

以上作品

where meter_serial = 21001652 AND ...")

以上作品。

where meter_serial = '".$variable."' AND ...")

以上不起作用

where meter_serial = ".$variable." AND ...")

以上不起作用

非常感谢。

2 个答案:

答案 0 :(得分:7)

使用占位符。不要乱用字符串连接。

my $get_meter_id = $dbh->prepare("SELECT * from t_readings where meter_serial=? AND ...");
my $foo = 21001652;
$get_meter_id->execute($foo) or die "Couldn't execute statement: ".$get_meter_id->errstr;

答案 1 :(得分:5)

怎么样:

my $get_meter_id = $dbh->prepare("SELECT * from t_readings where" .
     "meter_serial = ? AND ...");
$get_meter_id->execute($variable) or die "Couldn't execute statement: " . 
     $get_meter_id->errstr;
my $meter_reg_id = $get_meter_id->fetchrow_array();

进一步reading