郵便番号のCSVデータを nodejsを使って適当にmysqlに登録してみる
ありがちなんだけど 郵便番号のCSVデータを nodejsを使って登録してみる(手抜きですが)
データのダウンロードはこちら 郵便番号検索。
コマンドは以下を参照
MySQLに接続するユーザー名とパスワードの指定。
データベースの作成。
まずはDBを作成する
とりあえず試してみるだけなので、テーブルも手抜き(笑
A5Mk2にて root - mysql を指定して接続
CREATE DATABASE DEMO;
環境設定(追加のみ)
A5Mk2にて root - demo を指定して接続
CREATE TABLE POSTAL (
POSTAL char(8) CHARACTER SET utf8 DEFAULT NULL,
PREF char(20) CHARACTER SET utf8 DEFAULT NULL,
CITY char(40) CHARACTER SET utf8 DEFAULT NULL,
ADRLINE1 char(40) CHARACTER SET utf8 DEFAULT NULL,
ADRLINE2 char(40) CHARACTER SET utf8 DEFAULT NULL,
ADRLINE4 char(40) CHARACTER SET utf8 DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
地元県だと名前感あるので 17ISHIKA.CSV を使う
PS > npm install mysql
npm WARN nodedb@1.0.0 No description
npm WARN nodedb@1.0.0 No repository field.\+ mysql@2.14.1
PS >
var async = require('async');
var csv = require('csv');
var fs = require('fs');
var iconv = require('iconv-lite');
var mysql = require('mysql');var pool = mysql.createPool({
connectionLimit : 10,
host : 'localhost',
user : 'root',
password : 'passwd',
database : 'demo'
});// https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding
iconv.skipDecodeWarning = true;//pool.on('acquire', function (con) {
// console.log('Connection %d acquired', con.threadId);
//});// http://www.codexpedia.com/javascript/nodejs-mysql-pool-connection/
async.forEachSeries( fs.readFileSync('17ISHIKA.CSV', 'binary').toString().split('\n'), function (line, cb) {
line = iconv.decode(line, 'Shift_JIS'); // Shift_JIS -> utf8
if (line.length > 0) {
csv.parse(line, function(err, line){
csv.transform(line, function(line){
//console.log(line[2] + line[7] + line[8]);
return line;
}, function(err, line){
pool.getConnection(function(err, con) {
if (err) {
console.error('error connecting: ' + err.stack);
return;
}
var sql = "insert into postal (postal, city, adrline1 ) values ('"+line[0][2]+"','"+line[0][7]+"','"+line[0][8]+"');"
//console.log( "insert:" + sql);
con.query(sql, function (err, result) {
if (err) {
console.log("err:" + sql);
}
con.release();
cb();
});
});
});
});
} else {
console.log('END: ');
process.exit(0);
}
});select count(*) from postal -> 2552