DBIのbind_columns
SELECT文を使ってデータを取得する場合、DBIから配列やハッシュで取得する以外に「列と変数を bind する」という方法がある。
以下のようなテーブルがあるとする。
CREATE TABLE table1 ( id integer PRIMARY KEY, name text, email text );
結果をハッシュで取得する場合
my $dbh = DBI->connect("dbi:Pg:dbname=testdb", "hiramatsu", "hiramatsu"); my $sth = $dbh->prepare("SELECT id,name,email FROM table1"); $sth->execute(); while(my $row = $sth->fetchrow_hashref) { print "id: $row->{id}, name: $row->{name}, email: $row->{email}\n"; }
bind する場合
my $dbh = DBI->connect("dbi:Pg:dbname=testdb", "hiramatsu", "hiramatsu"); my $sth = $dbh->prepare("SELECT id,name,email FROM table1"); $sth->execute(); my $id = 0; my $name = ""; my $email = ""; $sth->bind_columns(\$id, \$name, \$email); while ($sth->fetch()) { print "id: $id, name: $name, email: $email\n"; }
id,name,email列をそれぞれ変数とbindしている。DBIのperldocには
「bindされた変数はパフォーマンスが良い」と書いてある。