LoginSignup
0
0

Postgresqlのcsvインポート・エクスポートメモ

Posted at

SQL Shellでインポート・エクスポート

  • スタートメニュー等から、SQL Shell (psql)を起動する(Enter何回か押して、パスワード入力して「postgres=#」が現れるとこまで行く)

image.png
image.png

test_tblをデスクトップにtest_tbl.csvとしてエクスポート(ヘッダーあり)

\COPY test_tbl TO 'C:\Users\ユーザー名\Desktop\test_tbl.csv' DELIMITER ',' CSV HEADER;

SQLの結果をデスクトップにtest_tbl.csvとしてエクスポート(ヘッダーあり)

\COPY (select * from test_tbl where id = 2330) TO 'C:\Users\ユーザー名\Desktop\test_tbl.csv' DELIMITER ',' CSV HEADER;

test_tblへデスクトップのtest_tbl.csv(ヘッダーあり)をインポート

(TOをFROMに変えるだけ)

\COPY test_tbl FROM 'C:\Users\ユーザー名\Desktop\test_tbl.csv' DELIMITER ',' CSV HEADER;

引数の参考
https://www.postgresql.jp/document/15/html/sql-copy.html

コマンドプロンプトでエクスポート

前提
・psqlのパスは通っていない
・デスクトップにtest_tbl.csvとしてエクスポート

コマンドプロンプト内にSQLを直接書く場合

-tと-Aをつけないと文字化けした

"C:\Program Files\PostgreSQL\16\bin\psql.exe" -h localhost -U postgres -d postgres -p 5432 -c "select * from public.test_tbl;" -t -A -F, > "C:\Users\ユーザー名\Desktop\test_tbl.csv"

SQLファイルを読み込んで実行する場合

デスクトップのsql.txtを読み込んで実行

"C:\Program Files\PostgreSQL\16\bin\psql.exe" -h localhost -U postgres -d postgres -p 5432 -f "C:\Users\ユーザー名\Desktop\sql.txt" -t -A -F, > "C:\Users\ユーザー名\Desktop\test_tbl.csv"

毎回パスワードを求められるのが面倒な場合は、環境変数にパスワードを設定するとパスワード入力しなくて済む

set PGPASSWORD=パスワード

引数の参考
https://www.postgresql.jp/document/15/html/app-psql.html

今後

  • コマンドプロンプトでヘッダーありでcsv出力する方法を調べる
  • メタコマンドのpsetについて調べる
0
0
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
0
0