【问题标题】:How to fetch results from a query using fetchall_arrayref in perl?如何在 perl 中使用 fetchall_arrayref 从查询中获取结果?
【发布时间】:2017-12-30 18:39:01
【问题描述】:

我的代码:

my $sql_query = "select Event_datetime,Event,User from logs";
my $sth = $dbh->prepare($sql_query);
$sth->execute();
$testResults = $sth->fetchall_arrayref();
foreach my $row (@$testResults) {
    ($Event_datetime,$Event,$User) = @$row;
    print $query->h2($ID);
}

我想使用一个for循环来获取这个查询的结果(一旦它被执行),这样每一行都有一个数字,即由于行是按顺序列出的,我需要通过它的行号来访问该行。

即第 1 行为 0;第 2 行是 1;第 3 行是第 2 行,依此类推...

例如:

for ($i=0; $i < $noOfRows; $i=$i+1) {
    ($ID,$Event_datetime,$Event,$User) = @$testResults;
    print $query->h3($ID, ' ,', $Event_datetime, ',', $Event, ',', $User );
}

但是,这个查询没有给我任何输出。如何通过行号访问特定行?

【问题讨论】:

  • use strict;use warnings; 添加到文件顶部。您没有展示可重现的示例。

标签: perl dbi


【解决方案1】:

你也可以看看Perl How to get the index of last element of array reference?

my $lastRowIdx = $#$testResults;
for (my $i=0 ; $i<=$lastRowIdx ; $i++ ) {
  my $rref = $testResults->[$i];
  print "@$rref\n";
} # endfor;

【讨论】:

    猜你喜欢
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    • 1970-01-01
    • 2014-03-23
    • 1970-01-01
    相关资源
    最近更新 更多