将Perl SQL查询的输出保存到哈希而不是数组

时间:2013-05-10 02:45:54

标签: mysql perl

我正在尝试在命令行的末尾添加一个参数,通过MySQL数据库运行该搜索,然后列出结果或者说没有找到任何内容。我试图通过将查询数据保存为哈希和数组来实现(这些是练习,我在PERL上非常新,脚本和尝试学习)。但是,我无法弄清楚如何用哈希做同样的事情。我确实希望SQL查询完成,然后将输出写入散列,以便不调用While函数。任何指导都将不胜感激。

#!/usr/bin/perl -w
use warnings;
use DBI;
use Getopt::Std;

&function1;
&function2;

if ($arrayvalue != 0) {
    print "No values found for '$search'"."\n"};

sub function1 {

getopt('s:');
$dbh = DBI->connect("dbi:mysql:dbname=database", "root", "password")
    or die $DBI::errstr;

$search = $opt_s;
$sql = $dbh->selectall_arrayref(SELECT Player from Players_Sport where Sport like '$search'")
or die $DBI::errstr;
@array = map { $_->[0] } @$sql;
$dbh->disconnect
    or warn "Disconnection failed": $DBI::errstr\n";

}

sub function2 {

@array;
$arrayvalue=();
print join("\n", @array, "\n");
if(scalar (@array) == 0) {
    $arrayvalue = -1
}
    else {$arrayvalue = 0;
};

}

2 个答案:

答案 0 :(得分:2)

请参阅selectall_hashref上的DBI文档。它返回对哈希引用哈希的引用。

使用语法

$dbh->selectall_hashref($statement, $key_field[, \%attri][, @bind_values])

所以这里有一个例子,它将返回什么/如何:

my $dbh = DBI->connect($dsn, $user, $pw) or die $DBI::errstr;

my $href = $dbh->selectall_hashref(q/SELECT col1, col2, col3
                                     FROM table/, q/col1/);

您返回的结构如下所示:

{
  value1 => {
      col1 => 'value1',
      col2 => 'value2',
      col3 => 'value3'
  }
}

因此,您可以执行以下操作来访问哈希引用:

my $href = $dbh->selectall_hashref( q/SELECT Player FROM 
                                      Players_Sport/, q/Player/ );

# $_ is the value of Player
print "$_\n" for (keys %$href); 

您可以单独访问每个哈希记录:

$href->{$_}->{Player} 

答案 1 :(得分:1)

来自documentation

$sql = $dbh->selectall_hashef("SELECT Player from Players_Sport where Sport like ?", 'Players_Sport_pkey', $sport_like_value);
my %hash_of_sql = %{$sql};