perl DBI,获得单个标量值的最快方法

问题描述 投票:3回答:2

我有这个代码来获取值。

简短的方法:

my $count = $dbh->selectrow_array("SELECT COUNT(name) AS RESCOUNT FROM users");

很长的路要走

my $sth = $dbh->prepare("SELECT COUNT(name) AS RESCOUNT FROM users");
$sth->execute() or die "$DBI::errstr";
my $count = $sth->fetchrow_array();
$sth->finish;

selectrow_array,fetchrow_array - >但我不需要数组。我检查了文档,但没有找到任何标记。只是阵列和散列的方法。我使用的方法足够快,但我只是好奇是否有更好,最快的方法从调用中获取单个值。或者这是最快的方式?

mysql perl dbi
2个回答
1
投票

最快的方法是使用fetchrow_arrayrefselectrow_arrayref,具体取决于您执行的执行次数。如果在循环中执行并且您有数千(或更确切地说是数十万)行,这只会产生影响。

当使用fetchrow_array时,它会每次都复制一次,这会减慢你的速度。还要记住,标量上下文的行为是only partly defined

如果在具有多个列的语句句柄的标量上下文中调用,则不确定驱动程序是返回第一列还是最后一列的值。所以不要这样做。

你也可以做bind_col,它与参考文献一起使用。

过去,大约10年或更久以前的DBI速度有一个很好的演示,我现在找不到。还可以看一下this very old Perlmonks post,它解释了相当多的性能。

请记住,只有在您确实需要优化时才应进行优化。大多数时候你不会。


1
投票

如果“现代”意味着“我最近才听说过它”,那么我觉得DBI的bind_col和bind_columns都很现代。来自DBI英雄蒂姆·邦斯的帖子让...

对于你的情况:

my $sth = $dbh->prepare("SELECT COUNT(name) AS RESCOUNT FROM users");
my $count = 0;
$sth->bind_col(1,\$count);  # bind to a reference to the variable
$sth->execute() or die "$DBI::errstr";
$sth->fetch;
print $count;

在循环中,SELECT语句返回多个记录:

my $sth = $dbh->prepare(qq{SELECT name FROM users WHERE zip_code == '20500'});
my $name = '';
$sth->bind_col(1,\$name);  # bind to a reference to the variable
$sth->execute() or die "$DBI::errstr";
while ($sth->fetch) {
    print $name, "\n";
}

使用bind_columns这有效:

my $sth = $dbh->prepare(qq{SELECT name,phone,address FROM users WHERE zip_code == '20500'});
my @fields = qw/name phone address/; 
# With a 'SELECT All * ...', get all columns with @{$sth->{NAME_lc}}
my %data;
$sth->bind_columns( \( @data{@fields} ) ); # \(...) gives references to its elements
$sth->execute() or die "$DBI::errstr";
while ($sth->fetch) {
    print "$data{name} lives at $data{address}, with phone $data{phone}.", "\n";
}

处理完设置后,循环很容易编写并快速运行。 (但是,基准)。

HTH,如果这与OP的问题陈述有太多分歧,请道歉。但这是将您返回的数据转换为您想要的变量形式的最简单,最直接的方法,因此您可以继续使用它做一些事情......

© www.soinside.com 2019 - 2024. All rights reserved.