【 Perl + MySQL 】

1.インストール
2.ドキュメントによる仕様の確認 (DBD)
3.接続と切断
4.行を返さないSQLの実行
5.行を返すSQLの実行
6.その他の情報の取得

ダウンロード
  • www.activestate.com より ActivePerl をダウンロードします

  • 今回のテストは ActivePerl 5.8.2 build 808 MSI で行います

  • インストールディレクトリは、C:\Perl とします

  • OS は Windows XP Home Edition です


  • インスール終了後、アプリケーションの追加と削除 でインストールされた事を確かめます

  • 環境変数 PATHc:\Perl\bin が存在する事を確認して、コマンドプロンプトより ppm を実行します

  • query * を実行してインストール済みのパッケージの一覧を確認しておきます
  • ppm> query *
    Querying target 1 (ActivePerl 5.8.2.808)
       1. ActivePerl-DocTools     [0.04] Perl extension for Documentation TOC Gene~
       2. ActiveState-Relocat~    [0.03] Relocate a Perl installation
       3. ActiveState-Rx          [0.60] Regular Expression Debugger
       4. Archive-Tar             [1.07] Manipulates TAR archives
       5. Compress-Zlib           [1.22] Interface to zlib compression library
       6. Data-Dump               [1.01] Pretty printing of data structures
       7. Digest-HMAC             [1.01] Keyed-Hashing for Message Authentication
       8. Digest-MD2              [2.03] Perl interface to the MD2 Algorithm
       9. Digest-MD4               [1.1] Perl interface to the MD4 Algorithm
      10. Digest-SHA1             [2.06] Perl interface to the SHA-1 Algorithm
      11. File-CounterFile        [1.01] Persistent counter class
      12. Font-AFM                [1.18] Interface to Adobe Font Metrics files
      13. HTML-Parser             [3.34] HTML parser class
      14. HTML-Tagset             [3.03] Data tables useful in parsing HTML
      15. HTML-Tree               [3.18] build and scan parse-trees of HTML
      16. IO-Zlib                 [1.01] IO:: style interface to Compress::Zlib
      17. libwin32                [0.21] A collection of extensions that aims to p~
      18. libwww-perl             [5.75] Library for WWW access in Perl
      19. MD5                     [2.02] Perl interface to the MD5 Algorithm (obso~
      20. PPM3                     [3.1] Perl Package Manager: locate, install, up~
      21. SOAP-Lite               [0.55] Library for Simple Object Access Protocol~
      22. Tk                   [800.024] A Graphical User Interface Toolkit
      23. URI                     [1.27] Uniform Resource Identifiers (absolute an~
      24. Win32-AuthenticateU~    [0.02] Win32 User authentication for domains
      25. XML-Parser              [2.34] A Perl module for parsing XML documents
      26. XML-Simple              [2.09] Easy API to read/write XML (esp config fi~
    
  • http://ppm.activestate.com/PPMPackages/zips/8xx-builds-only/Windows/ で、DBIDBD-mysql
    の最新バージョンを確認しておきます。

  •  
    DBI-1.39.zip
    DBD-mysql-2.9002.zip
    


    ppm> install DBI
    ====================
    Install 'DBI' version 1.39 in ActivePerl 5.8.2.808.
    ====================
    Downloaded 445877 bytes.
    Extracting 62/62: blib/arch/auto/DBI/Driver_xst.h
    Installing C:\Perl\site\lib\auto\DBI\dbd_xsh.h
     
     ( 省略 )
     
    Installing C:\Perl\bin\dbiproxy
    Installing C:\Perl\bin\dbiproxy.bat
    Successfully installed DBI version 1.39 in ActivePerl 5.8.2.808.
    


    ppm> install DBD-mysql
    ====================
    Install 'DBD-mysql' version 2.9002 in ActivePerl 5.8.2.808.
    ====================
    Downloaded 178803 bytes.
    Extracting 17/17: blib/arch/auto/DBD/mysql/mysql.lib
    Installing C:\Perl\site\lib\auto\DBD\mysql\mysql.bs
     
     ( 省略 )
     
    Installing C:\Perl\site\lib\DBD\mysql\INSTALL.pod
    Installing C:\Perl\site\lib\Mysql\Statement.pm
    Successfully installed DBD-mysql version 2.9002 in ActivePerl 5.8.2.808.
    
  • query DB* でインストールされた事を確かめます

  • ppm> query DB*
    Querying target 1 (ActivePerl 5.8.2.808)
      1. DBD-mysql    [2.9002] A MySQL driver for the Perl5 Database Interface (DB~
      2. DBI            [1.39] Database independent interface for Perl
    


    HTMLドキュメント
  • パッケージと共に、ドキュメントもインストールされます

  • C:\Perl\html\index.html で確認します


  • NAME
    DBD::mysql − Perl5 データベースインタフェースのための MySQL ドライバ − ( DBI )
     
    概要
        use DBI;
        $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port";
        $dbh = DBI->connect($dsn, $user, $password);
        $drh = DBI->install_driver("mysql");
           or
                                       {"host" => $host, "port" => $port});
        $sth = $dbh->prepare("SELECT * FROM foo WHERE bla");
           or
        $sth = $dbh->prepare("LISTFIELDS $table");
           or
        $sth = $dbh->prepare("LISTINDEX $table $index");
        $sth->execute;
        $numRows = $sth->rows;
        $numFields = $sth->{'NUM_OF_FIELDS'};
        $sth->finish;
        $rc = $drh->func('createdb', $database, $host, $user, $password, 'admin');
        $rc = $drh->func('dropdb', $database, $host, $user, $password, 'admin');
        $rc = $drh->func('shutdown', $host, $user, $password, 'admin');
        $rc = $drh->func('reload', $host, $user, $password, 'admin');
        $rc = $dbh->func('createdb', $database, 'admin');
        $rc = $dbh->func('dropdb', $database, 'admin');
        $rc = $dbh->func('shutdown', 'admin');
        $rc = $dbh->func('reload', 'admin');
    

    #!/usr/local/bin/perl
     
    print "Content-type: text/html; charset=Shift_JIS\n\n";
    print "<HTML><BODY>";
     
    # **********************************************************
    # サンプル
    # **********************************************************
    	use DBI;
     
    	$ret = eval{ $dbh = DBI->connect('DBI:mysql:lightbox:localhost', 'root', '') };
    	if ( !$ret ) {
    		print "接続エラーが発生しました";
    		exit();
    	}
     
    	$dbh->disconnect;
     
    print "</BODY></HTML>";
    


    $query = "create table 商品 (";
    $query .= "コード varchar(4) not null,";
    $query .= "表\示名 varchar(20),";
    $query .= "primary key(コード))";
    $ret = eval{ $dbh->do( $query ) };
    if ( !$ret ) {
    	print $dbh->{'mysql_error'};
    	exit();
    }
    
  • MySQL は日本語(Shift_JIS) 対応されているという前提です

  • 5C を含む漢字にはエスケープが必要です


  • $query = "select * from 商品";
    $sth = $dbh->prepare( $query );
    $ret = eval{ $sth->execute };
    if ( !$ret ) {
    	# 3種類のエラーメッセージの取得方法
    	print $dbh->{'mysql_error'} . "<br>";
    	print $dbh->errstr . "<br>";
    	print $sth->errstr . "<br>";
    	$sth->finish;
    	$dbh->disconnect;
    	exit();
    }
     
    # **********************************************************
    # fetchrow ( 配列 1 )
    # ドキュメントには記述されていません
    # **********************************************************
    while (@row = $sth->fetchrow) {
    	print "$row[0]/$row[1]<BR>\n";
    }
     
    # **********************************************************
    # fetchrow_array ( 配列 2 )
    # ドキュメントには記述されていません
    # **********************************************************
    $ret = eval{ $sth->execute };
    while (@row = $sth->fetchrow_array) {
    	print "$row[0]/$row[1]<BR>\n";
    }
     
    # **********************************************************
    # fetchrow_arrayref ( 配列リファレンス 1 )
    # **********************************************************
    $ret = eval{ $sth->execute };
    while ($row = $sth->fetchrow_arrayref) {
    	print "$$row[0]/$$row[1]<BR>\n";
    }
     
    # **********************************************************
    # fetchrow_arrayref ( 配列リファレンス 2 )
    # **********************************************************
    $ret = eval{ $sth->execute };
    while ($row = $sth->fetchrow_arrayref) {
    	print "$row->[0]/$row->[1]<BR>\n";
    }
     
    # **********************************************************
    # fetchrow_hashref() ( 連想配列リファレンス )
    # **********************************************************
    $ret = eval{ $sth->execute };
    while ($row = $sth->fetchrow_hashref()) {
    	print "$row->{\"コード\"}/$row->{\"表\示名\"}<BR>\n";
    	print $row->{"コード"}. "/" . $row->{"表\示名"} . "<BR>\n";
    }
     
    $sth->finish;
    


    # ******************************************************
    # 行数
    # ******************************************************
    $ret = eval{ $rows = $sth->execute };
    print "行数 = $rows<BR>\n";
     
    $numRows = $sth->rows;
    print "行数 = $numRows<br>";
     
    # ******************************************************
    # 列数
    # ******************************************************
    $num = $sth->{'NUM_OF_FIELDS'};;
    print "列数 = $num<BR>\n";
     
    # ******************************************************
    # 列名
    # ******************************************************
    $names = $sth->{'NAME'};
    for (my $i = 0;  $i < $num;  $i++) {
    	print $$names[$i] . "<BR>";
    }
     
    # ******************************************************
    # データ型
    # ******************************************************
    $names = $sth->{'mysql_type_name'};
    for (my $i = 0;  $i < $num;  $i++) {
    	print $$names[$i] . "<BR>";
    }
     
    # ******************************************************
    # 主キーかどうか
    # ******************************************************
    $flg = $sth->{'mysql_is_pri_key'};
    for (my $i = 0;  $i < $num;  $i++) {
    	print $$flg[$i] . "<BR>";
    }