CSVデータをPostgreSQLに一括挿入する方法
はじめに
Mac環境の記事ですが、Windows環境も同じ手順になります。環境依存の部分は読み替えてお試しください。
目的
この記事を最後まで読むと、次のことができるようになります。
| No. | 概要 | キーワード |
|---|---|---|
| 1 | PostgreSQL | COPY |
実行環境
| 環境 | Ver. |
|---|---|
| macOS Catalina | 10.15.3 |
| Python | 3.7.3 |
| PostgreSQL | 11.5 |
関連する記事
CSVデータの一括挿入
テーブル定義
t_feedback.sh
~# \d t_feedback;
Table "public.t_feedback"
Column | Type | Collation | Nullable | Default
------------+-----------------------------+-----------+----------+----------------------------------------
id | integer | | not null | nextval('t_feedback_id_seq'::regclass)
service | character varying(255) | | not null |
title | character varying(255) | | not null |
detail | character varying(255) | | not null |
created_at | timestamp without time zone | | |
updated_at | timestamp without time zone | | |
Indexes:
"t_feedback_pkey" PRIMARY KEY, btree (id)
CSVデータ
path/data.csv
id,service,title,detail,created_at,updated_at
1,service1,title1,detail1,2020-05-04 00:00:00,2020-05-04 00:00:00
2,service2,title2,detail2,2020-05-04 00:00:00,2020-05-04 00:00:00
3,service3,title3,detail3,2020-05-04 00:00:00,2020-05-04 00:00:00
4,service4,title4,detail4,2020-05-04 00:00:00,2020-05-04 00:00:00
5,service5,title5,detail5,2020-05-04 00:00:00,2020-05-04 00:00:00
COPYコマンド
copy.sh
~# \COPY {table name} FROM {csv file} WITH CSV HEADER
一括挿入
-
postgresにログインする
-
COPYコマンドで一括挿入する
insert.sh
~# SELECT * FROM t_feedback;
id | service | title | detail | created_at | updated_at
----+---------+-------+--------+------------+------------
(0 rows)
~# \COPY t_feedback FROM path/data.csv WITH CSV HEADER
COPY 5
~# SELECT * FROM t_feedback;
id | service | title | detail | created_at | updated_at
----+----------+--------+---------+---------------------+---------------------
1 | service1 | title1 | detail1 | 2020-05-04 00:00:00 | 2020-05-04 00:00:00
2 | service2 | title2 | detail2 | 2020-05-04 00:00:00 | 2020-05-04 00:00:00
3 | service3 | title3 | detail3 | 2020-05-04 00:00:00 | 2020-05-04 00:00:00
4 | service4 | title4 | detail4 | 2020-05-04 00:00:00 | 2020-05-04 00:00:00
5 | service5 | title5 | detail5 | 2020-05-04 00:00:00 | 2020-05-04 00:00:00
(5 rows)