use DBI;
my $dbh = DBI->connect(
DBI->connect_cached( # 永続的な環境(mod_perl など)で接続を貼続ける
データソース, ユーザー名, パスワード,
{ RaiseError => 0, PrintError => 1, AutoCommit => 1 },
) or croak qq{can't connect : $!};
・データソース
mysql
DBI:mysql:データベース名
postgresql
DBI:Pg:dbname=データベース名;host=/tmp;port=5432;
・オプション
RaiseError
データベース処理でエラー発生時、例外 die を発生させる。デフォルトは 0(=off)、
1(=on)にすると Internal Server Error を出力して停止。
PrintError
データベース処理でエラー発生時、エラーコードと警告メッセージを出力。
デフォルトは 1(=on)、0(=off)にすると Web サーバのエラーログに出力されない。
AutoCommit
オートコミット。デフォルトは 1(=on)。
ShowErrorStatement
エラー発生時、問題の SQL 文をログに出力。デフォルトは 0(=off)。
AutoInactiveDestroy
fork した際に安全に、データベース・ハンドルを破棄する。デフォルトは 0(=off)。
・戻り値
成功時 : データベース・ハンドル
失敗時 : undef
データベースへの接続のみを行うモジュール。
package DBConnect;
####################
# データベース接続
####################
use strict;
use warnings;
use Carp qw( croak );
use DBI;
use Class::Std;
{
# オブジェクトを扱う変数の型変換が無意味であることを警告する
use overload (
# 数値
q{0+} => sub {
croak q{オブジェクトを扱う変数の数値への型変換は無意味};
},
# 文字列
q{""} => sub {
croak q{オブジェクトを扱う変数の文字列への型変換は無意味};
},
# ブール値
q{bool} => sub {
croak q{オブジェクトを扱う変数のブール値への型変換は無意味};
},
# その他の演算には、perl の標準演算を使用
fallback => 1,
);
# Class::Std のコンストラクタにて、属性の宣言と初期化を同時に行う
# MySQL(MariaDB)接続
sub mysql_connect {
my $self = shift;
# 定数
my $dbname = 'データベース名';
my $ds = 'DBI:mysql:' . $dbname; # データソース
my $user = 'ユーザー名';
my $pw = 'パスワード';
my $dbh = DBI->connect(
$ds, $user, $pw,
{ RaiseError => 0, PrintError => 1, AutoCommit => 1 },
) or croak qq{can't connect : $!};
return $dbh;
}
# PostgreSQL 接続
sub postgresql_connect {
my $self = shift;
# 定数
my $dbname = 'データベース名';
my $ds = 'DBI:Pg:dbname=' . $dbname; # データソース
my $user = 'ユーザー名';
my $pw = 'パスワード';
my $dbh = DBI->connect(
$ds, $user, $pw,
{ RaiseError => 0, PrintError => 1, AutoCommit => 1 },
) or croak qq{can't connect : $!};
return $dbh;
}
# Class::Std のデストラクタにて、属性をガベージコレクション
sub DEMOLISH {
my $self = shift;
return;
}
}
1;
データベース・ハンドル取得
use DBConnect;
my $dbc_obj = DBConnect->new();
my $dbh = $dbc_obj->postgresql_connect();