LoginSignup
48

More than 5 years have passed since last update.

全国の郵便番号データを最速でMySQL(MariaDB)に入れてみる

Posted at

CentOS7です。

大まかな流れ

  1. MariaDBのインストール&起動
  2. 郵便局の郵便番号データのダウンロードページからCSVをダウンロード
  3. CSVファイルをUTF8かつ全角カナに変換
  4. MariaDBで郵便番号テーブルを作る
  5. LOAD DATA LOCAL INFILEでCSVファイルからインポート

まず何はともあれrootに。以下全部root作業

1. MariaDBをインストール&起動

# cat /etc/redhat-release
CentOS Linux release 7.1.1503 (Core)

MariaDBをインストールして、起動&自動起動設定&動作確認

# yum install mariadb-server
# systemctl restart mariadb.service
# systemctl enable mariadb.service

2. 郵便局の郵便番号データのダウンロード

ここにあります。
http://www.post.japanpost.jp/zipcode/dl/kogaki-zip.html

# yum install wget unzip
# wget http://www.post.japanpost.jp/zipcode/dl/kogaki/zip/ken_all.zip
# unzip ken_all.zip

3. CSVファイルをUTF8かつ全角カナに変換

元ファイルはsjisで半角カナありなので、UTFかつ全角カナに変換。
nkfをインストールするため、epelのリポジトリを有効にする。

# yum install epel-release
# yum install nkf
# nkf -w KEN_ALL.CSV > ken_all_u.csv

4. データベースとテーブルの作成

mysqlに接続

# mysql

ここからmysqlの操作
まずはDBとテーブルの作成、カラムは15個で大きさはテキトウ。

mysql
MariaDB [(none)]> create database sampledb default character set utf8; 
MariaDB [(none)]> use sampledb
MariaDB [(sampledb)]> 
create table zipcode (
 id int unsigned not null auto_increment,
 jiscode varchar(255),
 zipcode_old varchar(255),
 zipcode varchar(255),
 pref_kana varchar(255),
 city_kana varchar(255),
 street_kana varchar(255),
 pref varchar(255),
 city varchar(255),
 street varchar(255),
 flag1 tinyint,
 flag2 tinyint,
 flag3 tinyint,
 flag4 tinyint,
 flag5 tinyint,
 flag6 tinyint,
 primary key (id),
 key zipcode (zipcode)
);

5. LOAD DATA LOCAL INFILEでCSVファイルからインポート

mysql
MariaDB [(sampledb)]> 
LOAD DATA LOCAL INFILE '/root/ken_all_u.csv'
INTO TABLE zipcode 
FIELDS
    TERMINATED BY ','
    OPTIONALLY ENCLOSED BY '"'
    ESCAPED BY ''
LINES
    STARTING BY ''
    TERMINATED BY '\r\n'
(
 jiscode,
 zipcode_old,
 zipcode,
 pref_kana,
 city_kana,
 street_kana,
 pref,
 city,
 street,
 flag1,
 flag2,
 flag3,
 flag4,
 flag5,
 flag6
);

最後に確認

mysql
MariaDB [(sampledb)]> select * from zipcode limit 2 \G

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
48