郵便番号データベースを作成する
郵便番号検索はウェブアプリケーションを作る際には、もはや必須条件だよね。そこで今回はその郵便番号データベースの構築方法を紹介する。今回は、perlスクリプトを使用して、mysqlデータベースにデータを投入することに。
まずは郵便番号データを
日本郵政公社のホームページからダウンロードしてくる(
ダウンロードページ)。ダウンロード一覧から"全国一括"を選択してダウンロードする。ダウンロードしてきたlzhファイルを展開すると、中にken_all.csvが含まれているはずなので、これを作業ディレクトリに配置する。
次には、ダウンロードしてきたデータの各フィールドを保持できるようなデータベーステーブルを作る。まずは、mysqlスーパーユーザで、データベースの作成とユーザ権限の付与を実行する。下の例では、ユーザk-ozakiにパスワードpasswordでlocalhostからのzipデータベースへの全ての権限を与えるようにした。
$ mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2625 to server version: 3.23.58-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> create database zip;
mysql> grant all privileges on zip.* to k-ozaki@localhost.localdomain
mysql> identified by 'password' with grant option;
mysql> exit;
作成したユーザとパスワードで、データベースにアクセスできるか確認してみる
$ mysql -u k-ozaki -p zip
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2626 to server version: 3.23.58-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
アクセスができることを確認できたら、次にはテーブルを作成する
mysql> create table ZIP (
mysql> CODE VARCHAR(10),
mysql> OLD_ZIP VARCHAR(5),
mysql> ZIP VARCHAR(7),
mysql> PREFECTURE_KANA VARCHAR(255),
mysql> CITY_KANA VARCHAR(255),
mysql> STREET_KANA VARCHAR(255),
mysql> PREFECTURE VARCHAR(255),
mysql> CITY VARCHAR(255),
mysql> STREET VARCHAR(255));
mysql> exit
$ ./loadzip.pl
最後にデータが正しく登録されているか確認してみる。
$ mysql -u k-ozaki -p zip
Enter password:
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 2629 to server version: 3.23.58-log
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql> select count(*) from ZIP;
+----------+
| count(*) |
+----------+
| 121155 |
+----------+
1 row in set (0.00 sec)
mysql>