データベースから条件に合ったデータを検索するための命令として、SQLにはselectという命令があります。
全節までで使用した データベースegiのテーブルmeiboを用いて、いくつかのselect文を使用したプログラム例を次に示します。
【使用するSQL文】 select namae, addre from meibo |
【プログラム例】
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect("dbi:Pg:dbname=egi",``,``)
or die "Cannot connect: " , $DBI::errstr;
$sth = $dbh->prepare("select namae, addre from meibo ")
or die "Cannot prepare: " , $dbh->errstr();
$sth->execute() or die "Cannot execute: " , $sth->errstr();
print "-----------\n";
print " 名前 住所 \n";
print "-----------\n";
while ( @row = $sth->fetchrow_array() ){
print "$row[0] $row[1] \n";
}
print "-----------\n";
|
【プログラム実行結果】 [egi@myouga]$ perl cgirei1.pl ----------- 名前 住所 ----------- ハル 宇部市 ミミ 宇部市 ポチ 山口市 クー 宇部市 サチ 下関市 ----------- |
【備考】
print "$row[0] $row[1] \n";
は、
print "@row \n";
でも同じ結果となる。
|
【使用するSQL文】
select namae from meibo where toshi >= 3
|
【プログラム例】
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect("dbi:Pg:dbname=egi",``,``)
or die "Cannot connect: " , $DBI::errstr;
$sth = $dbh->prepare("select namae from meibo where toshi >= 3")
or die "Cannot prepare: " , $dbh->errstr();
$sth->execute() or die "Cannot execute: " , $sth->errstr();
print "------\n";
print " 名前 \n";
print "------\n";
while ( @row = $sth->fetchrow_array() ){
print "@row \n";
}
print "------\n";
|
【プログラム実行結果】 [egi@myouga]$ perl cgirei2.pl ------ 名前 ------ ポチ クー サチ ------ |
【注意事項】 特になし |
【使用するSQL文】
select * from meibo where namae='ミミ'
|
【プログラム例】
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect("dbi:Pg:dbname=egi",``,``)
or die "Cannot connect: " , $DBI::errstr;
$sth = $dbh->prepare("select * from meibo where namae='ミミ'")
or die "Cannot prepare: " , $dbh->errstr();
$sth->execute() or die "Cannot execute: " , $sth->errstr();
print "--------------------------\n";
print "名前 歳 住所 電話 \n";
print "--------------------------\n";
while ( @row = $sth->fetchrow_array() ){
print "@row \n";
}
print "--------------------------\n";
|
【プログラム実行結果】 [egi@myouga]$ perl cgirei3.pl -------------------------- 名前 歳 住所 電話 -------------------------- ミミ 2 宇部市 0836-33-3333 -------------------------- |
【備考】 上記プログラムでは、検索条件である名前「ミミ」がSQL文に埋め込まれている。これは、 あまり美しいプログラムとは言えない。なぜならば、この名前を次々に変更して検索したい 場合などは、すべてのselect文を定義しておかなくてはいけないから。そこで、select文の定 義では比較する値を?としておき、後でselect文を実行する際(executeする際)に値を渡す という方法をとる。このような方法をプレースホルダーと呼ぶ |
【プレースホルダーを用いたプログラム】
#!/usr/bin/perl
use DBI;
$dbh = DBI->connect("dbi:Pg:dbname=egi",``,``)
or die "Cannot connect: " , $DBI::errstr;
$sth = $dbh->prepare("select * from meibo where namae=?")
or die "Cannot prepare: " , $dbh->errstr();
$na="ミミ";
$sth->execute($na) or die "Cannot execute: " , $sth->errstr();
print "--------------------------\n";
print "名前 歳 住所 電話 \n";
print "--------------------------\n";
while ( @row = $sth->fetchrow_array() ){
print "@row \n";
}
print "--------------------------\n";
|
江木鶴子 : egi@ube-c.ac.jp