#navi(../)
* PerlでPostgreSQLに接続するサンプルコード [#r72dca88]
Perlを使用してPostgreSQLに接続するサンプルコードを以下に記します。~
#contents
#htmlinsertpcsp(db-top.html,db-sp.html)
使用した環境は以下の通りです。
- CentOS release 6.3 (Final)
- Perl v5.8.8
- PostgreSQL - 8.4.13
* 関連資料 [#s5921623]
-[[PostgreSQLをCentOSにインストールする>PostgreSQL/CentOSインストール]]
-[[PHPでPostgreSQLに接続する・pg_connect>PHP/PostgreSQLに接続する・pg_connect]]
-[[CPANのDBD::Pgがインストールできない場合の対処>PostgreSQL/DBD Pgがインストールできない場合の対処]]
-[[PerlでPostgreSQLにアクセスできるようにする・CentOS>Perl/PostgreSQLにアクセスできるようにする・CentOS]]
* PerlでPostgreSQLにアクセスするために必要なモジュールをインストールします。 [#ab86bdba]
CentOSの場合は、rootユーザになり以下のコマンドでPostgreSQLをアクセスするためのPerlモジュールをインストールすることができます。
yum -y install perl-DBI perl-DBD-Pg
* PostgreSQLに接続し現在の日付を表示するサンプルコード [#xb0f6436]
#ref(pg_connect.pl.zip)
#!/usr/bin/perl
use DBI;
# PostgreSQL
our $DB_NAME = "postgres";
our $DB_USER = "sakura";
our $DB_PASS = "sakura";
our $DB_HOST = "127.0.0.1";
our $DB_PORT = "5432";
my $dbh = DBI->connect("dbi:Pg:dbname=$DB_NAME;host=$DB_HOST;port=$DB_PORT","$DB_USER","$DB_PASS") or die "$!\n Error: failed to connect to DB.\n";
my $sth = $dbh->prepare("SELECT now();");
$sth->execute();
while (my $ary_ref = $sth->fetchrow_arrayref) {
my ($row) = @$ary_ref;
print $row , "\n";
}
$sth->finish;
$dbh->disconnect;
1;
上記のサンプルコードは、ホスト名、ユーザ名、パスワードを設定しています。~
pg_hba.confにより設定が変わると思いますので、みなさんの環境にあう設定に変更してください。
#htmlinsertpcsp(db-btm.html,db-sp.html)