Perl DBI where IS NULL with undefined variable
Perl DBI where IS NULL with undefined variable
我有一个 perl
DBI
mysql
查询,如下所示:
my $rows = get_rows(
"select id from table where column1=?, column2=? and column3=?",
$var1,$var2,$var3
);
sub get_rows {
my $sql = shift;
my @vars = @_;
my $sth = $dbh->prepare($sql);
$sth->execute(@vars);
my $rows = $sth->fetchall_arrayref();
$sth->finish();
return $rows;
}
我 运行 这是为了检查是否存在包含这些变量的特定行。然而,我遇到的问题是处理 NULL 值。这些必须选择为 IS NULL
而不是 =?
,这通常会错过包含 NULL 值的行。例如,如果变量 1、2 和 3 包含 '12'
、'23'
和 undef
,而 table
包含 12
、23
和 NULL
然后查询 returns 没有结果。有没有一种简单的方法可以将 undef 值转换为 IS NULL
值 DBI
?
这记录在 DBI 下的 NULL 值。
$sql_clause = defined $age? "age = ?" : "age IS NULL";
$sth = $dbh->prepare(qq{
SELECT fullname FROM people WHERE $sql_clause
});
$sth->execute(defined $age ? $age : ());
我有一个 perl
DBI
mysql
查询,如下所示:
my $rows = get_rows(
"select id from table where column1=?, column2=? and column3=?",
$var1,$var2,$var3
);
sub get_rows {
my $sql = shift;
my @vars = @_;
my $sth = $dbh->prepare($sql);
$sth->execute(@vars);
my $rows = $sth->fetchall_arrayref();
$sth->finish();
return $rows;
}
我 运行 这是为了检查是否存在包含这些变量的特定行。然而,我遇到的问题是处理 NULL 值。这些必须选择为 IS NULL
而不是 =?
,这通常会错过包含 NULL 值的行。例如,如果变量 1、2 和 3 包含 '12'
、'23'
和 undef
,而 table
包含 12
、23
和 NULL
然后查询 returns 没有结果。有没有一种简单的方法可以将 undef 值转换为 IS NULL
值 DBI
?
这记录在 DBI 下的 NULL 值。
$sql_clause = defined $age? "age = ?" : "age IS NULL";
$sth = $dbh->prepare(qq{
SELECT fullname FROM people WHERE $sql_clause
});
$sth->execute(defined $age ? $age : ());