我正在编写一个perl脚本,它从mysql表中读取一些数据。这是原始程序的缩短版本:
#!/usr/bin/perl -w
use strict;
use warnings;
use DBI;
#db-name, user-name and pw are hidden here.
#In the real programm this part works fine.
my $dbh = DBI->connect('DBI:mysql:database=***;host=localhost','***','***');
#in the real script $from and $amount are parameters
#that are sent to this program from another source
my $from = 0;
my $amount = 5;
my $sql = 'SELECT `RefID` FROM `referenz` WHERE `RefID` > ? ORDER BY `RefID` ASC LIMIT 0,?;';
my $sthGetData = $dbh->prepare($sql);
$sthGetData->execute($from,$amount);
while (my $ref = $sthGetData->fetchrow_hashref()) {
if (defined($ref->{'RefID'})) {
print $ref->{'RefID'}."\n";
}
}
$dbh->disconnect();
exit(0);
问题似乎是?
- 签署sql语句的LIMIT
- 子句:
LIMIT 0,?
声明中有一个类似的?
- 短语:
WHERE `RefID` > ?
但这没问题。我已经在其他脚本中多次这样做了。它工作正常。
当我执行脚本时,我收到此错误:
DBD::mysql::st execute failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''5'' at line 1 at ./problem.pl line 17.
看起来好像$sthGetData->execute($from,$amount);
在每个绑定到语句的值周围添加了单引号,从而导致
LIMIT 0,'5'
而不是
LIMIT 0,5
那么,我怎样才能避免出现此错误?如何将变量值绑定到mysql语句中的limit-clause?
Server-Typ: MySQL
Server Version: 5.6.19-0ubuntu0.14.04.1 - (Ubuntu)
答案 0 :(得分:2)
LIMIT的参数不是表达式,因此它不能占用占位符。
LIMIT {[offset,] row_count | row_count OFFSET offset}
LIMIT 0,?
与LIMIT 0,4+4