Archive for 9月 18th, 2012

  1. Hello, DBI(Perl) World!

    Posted on 9月 18th, 2012 by cx20

    DBI

    DBI は Perl 向けの Database Interface(API)である。
    各データベースドライバを介することで、様々な DBMS への接続が可能となっている。

    ソースコード(Perl + DBI + ODBC + SQL Server)

    use strict;
    use DBI;
     
    my $dbh = DBI->connect('dbi:ODBC:Driver={SQL Server};Server=(local)', 'sa', 'P@ssW0rd');
    my $sth = $dbh->prepare("SELECT 'Hello, DBI World' AS Message");
    $sth->execute();
     
    while (my $row = $sth->fetchrow_array) {
        print "Message", "n";
        print "-------------------n";
        print $row, "n";
    }
    $sth->finish();
    $dbh->disconnect();

    ソースコード(Perl + DBI + MySQL)

    use strict;
    use DBI;
     
    my $dbh = DBI->connect('dbi:mysql:test', 'root', 'P@ssW0rd');
    my $sth = $dbh->prepare("SELECT 'Hello, DBI World' AS Message");
    $sth->execute();
     
    while (my $row = $sth->fetchrow_array) {
        print "Message", "n";
        print "-------------------n";
        print $row, "n";
    }
    $sth->finish();
    $dbh->disconnect();

    実行方法(Windows)

    C:¥> perl hello.pl

    実行結果

    Message
    -----------------
    Hello, DBI World!