开发者

Using Perl and MySql, how can I check for an empty result?

开发者 https://www.devze.com 2023-03-15 20:35 出处:网络
Way oversimplified example: # Get Some data $query = $db->prepare(qq{ select * from my_table where id = \"Some开发者_StackOverflow Value\"

Way oversimplified example:

# Get Some data
$query = $db->prepare(qq{
    select * from my_table where id = "Some开发者_StackOverflow 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}";
    }
};

Looking for the code for "THE QUERY HAS RETURNED A RESULT" up there. I'd like to avoid using count(*) in my SQL if possible, since that will require a "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";
}

Alternative:

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;
}

Simpler code at the expense of memory:

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

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


Looks to me like your check for the query result is redundant. Your while loop will evaluate 'false' if there is no row to fetch.


old/wrong answer

If you are using DBI with DBD::mysql then $query->rows; will return you the number of rows, selected (or affected on a writing statement) by your statement.

EDIT

Please don't use that and have a look at the comment to this answer by @Luke The Obscure

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号