Perlで、DBIモジュールを使って、データベースをアクセスするサンプルプログラムです。 データベースは、PostgreSQLを使っています。
カーソルを使って、SQL文の結果を1件ずつ処理するサンプルです。
#!/usr/local/bin/perl
use strict;
use DBI;
my ($dbh, $sth);
my ($data_source, $user_name, $sql);
my ($id, $name, $zip, $addr, $tel);
$data_source = 'dbi:Pg:dbname=addr';
$user_name = 'joe';
$dbh = DBI->connect($data_source, $user_name) || die $dbh->errstr;
$sql = 'select * from addr;';
$sth = $dbh->prepare($sql) || die $dbh->errstr;
$sth->execute() || die $sth->errstr;
while (($id, $name, $zip, $addr, $tel) = $sth->fetchrow_array()) {
print "$id, $name, $zip, $addr, $tel\n";
}
die $sth->errstr if $sth->err;
$sth->finish();
$dbh->disconnect();
|
selectallメソッドを使って、SQL文の結果を配列でまとめて処理するサンプルです。 SQL文の実行結果は、表として扱われるため、データは正規化されないので、SQLでは標準化されていません。 しかし、性能的に差が出るため、よく使われます。
#!/usr/local/bin/perl
use strict;
use DBI;
my ($dbh, $sth);
my ($data_source, $user_name, $sql);
my ($id, $name, $zip, $addr, $tel);
my ($ary, $num, $i);
$data_source = 'dbi:Pg:dbname=addr';
$user_name = 'joe';
$dbh = DBI->connect($data_source, $user_name) || die $dbh->errstr;
$sql = 'select * from addr;';
$ary = $dbh->selectall_arrayref($sql) || die $dbh->errstr;
$num = @$ary;
for ($i = 0; $i < $num; $i++) {
print "$ary->[$i][0], $ary->[$i][1], $ary->[$i][2], ";
print "$ary->[$i][3], $ary->[$i][4]\n";
}
$dbh->disconnect();
|