如何在变量中存储使用SELECT返回的行数

时间:2018-02-27 10:05:51

标签: mysql sql perl

我想将SELECT语句返回的行数存储在变量中,因为我需要计数才能进行进一步的计算。 我尝试使用COUNT函数,但我不知道如何将它存储在变量中。请帮帮我。任何替代方法也会这样做。 提前谢谢。

 #!C:/Perl64/bin/Perl.exe

 use warnings;
 use strict;
 use autodie;
 use Data::Dumper;
 use DBI;

 my $db="hnf1a";
 my $user="root";
 my $password="";
 my $host="localhost";
 my $dbh = DBI->connect("DBI:mysql:database=$db:$host",$user,$password);
 my $sth=$dbh->prepare('SELECT COUNT ano AS $b FROM mody where ano = ?');
 my $input = <stdin>;
 my @num = split //, $input;

 for my $num(@num){     
 say "rows matching input <$num>:";     
 $sth->execute($num);   
 while(my@data = $sth->fetchrow_array){     
 say"\t@data";  
 }}

因此,在我的代码中,我需要找到一种方法来存储返回的行数。

2 个答案:

答案 0 :(得分:0)

use strict;
use warnings;
use 5.012;

use DBI;

my $dbh = DBI->connect('dbi:SQLite:dbname=:memory:', '', '', {
    RaiseError => 1,
    PrintError => 0,
}) or die $DBI::errstr;

$dbh->do(q{
    create table mody (
        ano int
    )
});

my $sth = $dbh->prepare(q{insert into mody (ano) values (?)});

for (1 .. 100) {
    $sth->execute(int(rand(10)));
}

chomp(my $input = <STDIN>);
my @numbers = split(//, $input);

$sth = $dbh->prepare(q{select count(*) from mody where ano = ?});

for my $num (@numbers) {
    $sth->execute($num);
    my $count = $sth->fetchrow_array;

    say "$num: $count";
}

答案 1 :(得分:-2)

DBD :: mysql驱动程序有一个rows()方法,可以返回结果的计数:

$sth = $dbh->prepare( ... );
$sth->execute($num); 
$rowsCount = $sth->rows;

如果你想存储它,你可以这样做:

$rowsCount[$num] = $sth->rows;

如果你想总结一下:

my $rowsCount = 0

之前

for my $num(@num)&lt; -

然后你可以写:

$rowsCount += $sth->rows;