使用Perl和MySql,如何检查空结果?

前端之家收集整理的这篇文章主要介绍了使用Perl和MySql,如何检查空结果?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
方式过于简单的例子:

# Get Some data
$query = $db->prepare(qq{
    select * from my_table where id = "Some Value"
});
$query->execute;

# Iterate through the results
if ( *THE QUERY HAS RETURNED A RESULT* ) {
    print "Here is list of IDs ";
    while ($query_data = $query->fetchrow_hashref) {
        print "$query_data->{id}";
    }
};

在那里寻找“THE QUERY HURN RETURN A A RESULT”的代码.如果可能的话,我想避免在我的sql中使用count(*),因为这需要“group by”.

解决方法

my $sth = $dbh->prepare($stmt);
$sth->execute();

my $header = 0;
while (my $row = $sth->fetchrow_hashref) {
    print "Here is list of IDs:\n" if !$header++;
    print "$row->{id}\n";
}

替代方案:

my $sth = $dbh->prepare($stmt);
$sth->execute();

my $row = $sth->fetchrow_hashref;
print "Here is list of IDs:\n" if $row;
while ($row) {
    print "$row->{id}\n";
    $row = $sth->fetchrow_hashref;
}

更简单的代码以牺牲内存为代价:

my $ids = $dbh->selectcol_arrayref($stmt);

if (@$ids) {
    print "Here is list of IDs:\n";
    print "$_\n" for @$ids;
}

猜你在找的Perl相关文章