Perl でMySQL接続メモ
★前回作ったサンプルデータ(http://d.hatena.ne.jp/mk_1211/20120929/1348880579)をもとに、PerlのDBIとDBD::mysqlモジュールを使ってみました。
#!/usr/bin/perl use strict; use warnings; use DBI; my $hostname = "localhost"; my $user = "user1"; my $passwd = "abcd1234"; my $database = "db1"; my $postal = shift; $postal =~ s/-//g; die "Usage: $0 POSTAL_CODE" unless defined $postal; #データベースへ接続 my $dsn = "DBI:mysql:database=$database;host=$hostname;mysql_read_default_file=/etc/my.cnf"; my $dbh = DBI->connect($dsn, $user, $passwd, { 'RaiseError' => 1, 'PrintError' => 0, 'AutoCommit' => 1}); eval { #行の選択 my $sth = $dbh->prepare("SELECT * FROM tokyo_postal_code WHERE postal_code = ?"); $sth->execute("$postal"); #データの取得 while (my $arr_ref = $sth->fetchrow_arrayref) { my $prefecutre = $$arr_ref[6]; my $city = $$arr_ref[7]; my $town = $$arr_ref[8]; $town =~ s/以下に掲載がない場合|(次のビルを除く)//g; print $prefecutre.$city.$town ."\n"; } }; die "Error: $@" if($@); $dbh->disconnect();
★実行結果
引数に東京の郵便番号を指定すると、住所がでる感じです。
[root@ha-01 Perl_Script]# ./postal_code_get.pl 100-0002 東京都千代田区皇居外苑 [root@ha-01 Perl_Script]#