【问题标题】:Why do we need Perl DBI functions that return 1 row?为什么我们需要返回 1 行的 Perl DBI 函数?
【发布时间】:2013-08-13 01:16:11
【问题描述】:

我正在研究 Perl 的 DBI,看到了以下方法:
selectrow_array
selectrow_arrayref
selectrow_hashref
所有这些都从结果集中返回 1 行。所以我不明白它们有什么用处。它们是否可以替代LIMIT 1?

【问题讨论】:

  • 下面的答案很好。如果查询会返回很多行,您仍应将 LIMIT 1 添加到查询中,这样服务器就可以避免选择很多行并将其发送回客户端。

标签: perl dbi dbix-class


【解决方案1】:

有很多有用的示例只获取一行,这些功能简化了搜索过程。例如,获取结果集的计数

my $sql = "select count(*) from people where age>?";    
my ($count) = $dbh->selectrow_array($sql, undef, 42);

替代方法需要:准备、绑定和执行、获取和完成。

【讨论】:

  • 这也表明我只期待一行,而不必查看$sql。
【解决方案2】:

是的,当您只需要选择 1 行时,它只是使程序更小的语法糖。正如手册所说:

selectrow_hashref - 此实用方法结合了“准备”、“执行”和 "fetchrow_hashref"

所以,不要写:

$sql = qq{
    SELECT
        project.domain,
        project.pages_to_save,
        project.pages_to_check,
        IFNULL(project.no_exact_result, 0) AS no_exact_result
    FROM
        project
    WHERE
        project.id=?
};
my $sth = $dbh->prepare($sql);
$sth->execute($project_id);
my $values_ref = $sth->fetchrow_hashref();
$sth->finish();

你可以写:

$sql = qq{
    SELECT
        project.domain,
        project.pages_to_save,
        project.pages_to_check,
        IFNULL(project.no_exact_result, 0) AS no_exact_result
    FROM
        project
    WHERE
        project.id=?
};
my $values_ref = $sth->selectrow_hashref($sql, undef, $project_id);

【讨论】:

  • 你怎么知道project.id=?会返回1行?
  • @Jim 因为在我的数据库中 id 是项目表中的主键
猜你喜欢
  • 2013-04-28
  • 1970-01-01
  • 2022-01-17
  • 2019-06-14
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多