14.9 DBIを使用してSQLコマンドを実行する

Oracle, Sybase, mSQL, MySQLなどのデータベースシステムにSQLクエリを送信し、その結果を処理したい。

  • CPANで公開しているDBI(DataBase Interface), DBD(DataBase Driver)モジュールを使用する
use DBI;

$dbh = DBI->connect('dbi:driver:database', 'usename', 'auth', 
  { RaiseError => 1, AutoCommit => 1 });

$dbh->do($NON_SELECT_SQL_STATEMENT);

$result = $dbh->selectall_arrayref($SELECT_SQL_STATEMENT);

$sth = $dbh->prepare($SQL_SELECT_STATEMENT);
$sth->execute();

while (@row = $sth->fetchrow_array) {
  # ...
}

$dbh->disconnect();