2010年2月9日火曜日

覚書 PERLでのDBアクセスについて

★DBI

①CPANからダウンロードしてインストール

CPAN : http://search.cpan.org
DBI : DBI-1.609.tar.gz
DBD::PG : DBD-Pg-2.16.1.tar.gz

 インストールはそれぞれ以下のように行う。
$ tar zxvf DBI-1.609.tar.gz
$ cd DBI-1.609
$ perl Makefile.PL
$ make
$ su
# make install

※gcc がはいっていないため、make でエラー
→ yum install gcc
再度make

$ tar zxvf DBD-Pg-2.16.1.tar.gz
$ cd DBD-Pg-1.49
$ perl Makefile.PL
$ make
$ su
# make install

※perl Makefile.PLでpg_config のパスを聞かれるがない・・・
→yum install postgresql-devel
http://www13.big.or.jp/~rinken/kaze/arc/200703.html

use DBI;

$dbh = DBI->connect("dbi:Pg:dbname=$dbname;host=$host;port=$port;" .
"options=$options;tty=$tty", "$username", "$password");


※makeでエラー
  →version-0.80.tar.gzをインストールして、再度DBI、DBDをインストールして回避
  http://groups.google.co.jp/group/spreadsheet-writeexcel/browse_thread/thread/4ecf8ae7fbe4f656?pli=1

★CGIからのDB接続
・DB接続をパスワード接続に変更
  centOS.txt参照


★エラートラップ(CGI::Carp)の利用

★テストスクリプト
#!/usr/bin/perl
#
# DBI のテスト
# 検索条件を指定してPostgreSQLにアクセスする
#

use DBI;

$dbname = "hoge";
$dbusername="name";
$dbpassword="passwd";

$sql="";
$user_id = "userid";

$dbh = DBI->connect("DBI:Pg:dbname=$dbname", $dbusername, $dbpassword);

$sql = "select count(*) from auth_tbl where user_id = ?";

#print $sql;

$sth = $dbh->prepare($sql) or die "can not execute: ". $sth->errstr();
$sth->execute($user_id) or die "Cannot execute: ".$sth->errstr();

@row;

#while (@row = $sth->fetchrow_array()) {
# print join(",", @row). "\n";
#}

@row = $sth->fetchrow_array();
print "count[".@row."]";

if ($row[0] >= 1) {
print "あったよー";
} else {
print "ない・・・";
}

$sth->finish();

0 件のコメント: