8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

大量のCSVデータをバルクインサート文に変換する

8
Last updated at Posted at 2024-03-09

概要

大量のCSVデータをバルクインサート文に変換する方法を説明します。
この記事ではawkコマンドを使います。

サンプルデータ

sample.csv
1, "大阪府", 1000
2, "兵庫県", 800
3, "京都府", 700
4, "奈良県", 600
5, "和歌山県", 500
6, "滋賀県", 400
7, "三重県",300

サンプルデータをこんな形にしたい

insert.sql
INSERT INTO SAMPLE_TABLE VALUES
(1, "大阪府", 1000),
(2, "兵庫県", 800),
(3, "京都府", 700);
INSERT INTO SAMPLE_TABLE VALUES
(4, "奈良県", 600),
(5, "和歌山県", 500),
(6, "滋賀県", 400);
INSERT INTO SAMPLE_TABLE VALUES
(7, "三重県",300);

バルクインサート文の説明

  • この例では一度にインサートする行を3行とする。(実用の場合だと数千〜数万行とかになります)
  • 3行ごとに「INSERT INTO SAMPLER_TALBE VALUES」を入れる
  • CSVの各行を丸カッコで囲む
  • CSVの行末はカンマですが、3行に達した場合はセミコロンにする
  • 最後のCSV行はセミコロンで終える

awkコマンドのサンプル

awk -v count=3 -v line_count="$(wc -l < sample.csv)" '
{
    # 1/3行毎に入れる
    if (NR % count == 1) {
        print "INSERT INTO SAMPLE_TABLE VALUES";
    }

    # 通常のカンマで終わる行、3/3行目と最終行は除く
    if (NR % count != 0 && NR != line_count) {
        print "(" $0 "),";
    }

    # 3/3行毎にセミコロンにする、最終行は除く
    if (NR % count == 0 && NR != line_count) {
        print "(" $0 ");";
    }

}
END {
    # 最終行は必ずセミコロン
    print "(" $0 ");";
}
' sample.csv

必要に応じてファイル出力をリダイレクトすればOK

変数説明

コマンドライン引数 -vで、一度にインサートする行をcountに設定します。
同様にsample.csvの総行数をline_countに設定します。
現在の行数がNRに入ります。
処理中のsample.csvの1行が$0に入ります。

最後に

awkコマンドはlinuxやMacに標準インストールされていることと、大量のデータでも高速に処理してくれる点が有難いです。

8
2
0

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
8
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?