select
fetchとselect
selectrow_array
は
prepare
excute
fetchrow_array
の処理をまとめたメソッド
DBIの使い方
#!/usr/bin/perl
use DBI;
my $data_source = 'DBI:mysql:test:localhost:3306';
my $user = 'user';
my $pass = 'pass';
my $dbh = DBI->connect($data_source,$user,$pass);
# いろいろ
$dbh->disconnect;
select*
col1 | col2 | col3 |
---|---|---|
a | A | testA |
b | B | testB |
c | C | testC |
d | D | testD |
e | E | testE |
selectrow_array
SELECTした1行目のレコードの配列を返す
my $stm = "select * from test";
my @row_array=$dbh->selectrow_array($stm);
print join (",",@row_array) . "\n";
---
a,A,testA
selectrow_arrayref
SELECTした1行目のレコードを配列のリファレンスで返す
my $stm = "select * from test";
my $row_arrayref=$dbh->selectrow_arrayref($stm);
print join (",",@$row_arrayref) . "\n";
---
a,A,testA
selectrow_hashref
取得した1行目のレコードをハッシュのリファレンスで返す
my $stm = "select * from test";
my $row_hashref=$dbh->selectrow_hashref($stm);
for my $name (sort keys %$row_hashref) {
my $value = $row_hashref->{$name};
print "$name:$value\n";
}
---
col1:a
col2:A
col3:testA
selectcol_arrayref
SELECTしたレコードの1列目のカラムを配列のリファレンスで返す
my $stm = "select * from test";
my $col_arrayref=$dbh->selectcol_arrayref($stm);
print join (",",@$col_arrayref) . "\n";
---
a,b,c,d,e
selectall_arrayref
取得したすべてのレコードを二次元配列のリファレンスで返す
my $stm = "select * from test";
my $all_arrayref=$dbh->selectall_arrayref($stm);
for my $aar (@$all_arrayref){
print join (",",@$aar) . "\n";
}
---
a,A,testA
b,B,testB
c,C,testC
d,D,testD
e,E,testE
selectall_hashref
指定カラムの値をキーにしたハッシュリファレンスを返す
バリューはまたハッシュリファレンスになっていて、カラム名のキーとカラム値のバリューを持つ
my $stm = "select * from test";
my $all_hashref=$dbh->selectall_hashref($stm,'col1');
for my $hashref (sort keys %$all_hashref) {
print "$hashref\n";
for my $name (sort keys %{$all_hashref->{$hashref}}) {
my $value = $all_hashref->{$hashref}{$name};
print "$name:$value\n";
}
}
---
a
col1:a
col2:A
col3:testA
b
col1:b
col2:B
col3:testB
c
col1:c
col2:C
col3:testC
d
col1:d
col2:D
col3:testD
e
col1:e
col2:E
col3:testE
参考
Perl DBI - dbi.perl.org
DBI - search.cpan.org
Perlの配列とハッシュを自由に扱う - サンプルコードによるPerl入門
データベースハンドル | Smart