Mysql 如何在变量中存储使用SELECT返回的行数
我想将SELECT语句返回的行数存储在一个变量中,因为我需要进一步计算的计数。 我尝试使用COUNT函数,但不知道如何将其存储在变量中。请帮帮我。任何替代方法都可以。 提前谢谢Mysql 如何在变量中存储使用SELECT返回的行数,mysql,sql,perl,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
#!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";
}}
因此,在我的代码中,我需要找到一种方法来存储返回的行数。DBD::mysql驱动程序有一个可以返回结果计数的rows方法:
$sth = $dbh->prepare( ... );
$sth->execute($num);
$rowsCount = $sth->rows;
如果要存储它,可以执行以下操作:
$rowsCount[$num] = $sth->rows;
如果要求和:
我的$rowsCount=0我确实尝试过使用该方法。但是我想不出一种方法来存储它在一个变量中。你是说数组,还是想把它显示为与输入匹配的行?不,像数组一样。我需要在以后的代码中使用这个计数值。这个变量确实被打印出来了,但我如何得到总行数的总和呢?它确实给出了它作为1行返回1行返回您是否会在每次编辑后添加其他问题-_-从哪个查询返回的行数?看起来您可能正在为每个输入运行多个。到目前为止你试过什么?我没有看到任何代码表明您试图执行任何请求帮助的操作。抱歉,我错过了这一行。我已经编辑了这篇文章。select ano查询中的行AS$b用于什么?通常,您会写入SELECT COUNT*。。。如果您想知道匹配行的数量。另外,stdin不是标准I/O句柄之一。您可能指的是STDIN。为了将计数的行存储在一个变量中,我将其用作$b。
$rowsCount += $sth->rows;
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";
}