PostgreSQLのCSVからのインポート処理についてのまとめ

-- 「\」1つではエスケープされるのでだめ
COPY tablename FROM 'C:\test\testdata.csv' WITH CSV;
-- WARNING:  nonstandard use of escape in a string literal
-- ERROR:  could not open file "C:testtestdata.csv" for reading: No such file or directory

-- 「\」2つでもなぜかエラーが出てだめ、ではなくて、警告が出るが実行はOK
COPY tablename FROM 'C:\\test\\testdata.csv' WITH CSV;
-- WARNING:  nonstandard use of \\ in a string literal
-- HINT:  Use the escape string syntax for backslashes, e.g., E'\\'.

-- ヒントにあるように「E」をつければ警告なしで実行OK
COPY tablename FROM E'C:\\test\\testdata.csv' WITH CSV;

-- パスに日本語が入っているとだめ(マルチバイトへの何らかの対応が必要?)
COPY tablename FROM 'C:/Documents and Settings/User/デスクトップ/testdata.csv' WITH CSV;
-- ERROR:  could not open file "C:/Documents and Settings/User/デスクトップ/testdata.csv" for reading: No such file or directory

-- 文字コードがファイルとDBで異なっていてもエラーとなります。
-- ERROR: invalid byte sequence for encoding "UTF8"

--EXCELで作成したCSVだとShift-JISになってしまうので、エディタで変換して保存し直すか、下記にて対応
SET client_encoding TO 'SJIS';
COPY tablename FROM 'C:/test/testdata.csv' WITH CSV;

デミリタを変えれば、ダブルコーテーション問題は解決。
・・・と思っていたら、
ERROR: extra data after last expected column
と、エラーメッセージが出力される。

結論。

COPY test FROM '/home/postgres/test.csv' WITH CSV;

で解決。

インポートは、

set client_encoding to ‘SJIS′;
COPY articles FROM E'C:\\tmp\\articles.txt' with CSV;

でOK。