1
3

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 5 years have passed since last update.

CSVデータをPostgreSQLに一括挿入する方法

1
Posted at

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

一括挿入

  1. postgresにログインする

  2. 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)
1
3
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
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?