我的 SQL 腳本如下所示
create table "cad".yield_name
(
yield_id int primary key,
yield_name varchar,
yield_name_f varchar
);
copy cad.yield_name
from '/data/cad/base/YIELD\ NAME.csv'
delimiter ',' csv header;
如您所見,我正在匯入一個名為 的檔案'/data/cad/base/YIELD\ NAME.csv',當我執行ls -ltr.
total 30724
-rw-r--r-- 1 postgres postgres 578264 Aug 31 2015 CONVERSION FACTOR.csv
-rw-r--r-- 1 postgres postgres 1155 Aug 31 2015 FOOD GROUP.csv
-rw-r--r-- 1 postgres postgres 761846 Aug 31 2015 FOOD NAME.csv
-rw-r--r-- 1 postgres postgres 2850 Aug 31 2015 FOOD SOURCE.csv
-rw-r--r-- 1 postgres postgres 12740 Aug 31 2015 NUTRIENT NAME.csv
-rw-r--r-- 1 postgres postgres 2229 Aug 31 2015 NUTRIENT SOURCE.csv
-rw-r--r-- 1 postgres postgres 162305 Aug 31 2015 REFUSE AMOUNT.csv
-rw-r--r-- 1 postgres postgres 4196317 Aug 31 2015 REFUSE NAME.csv
-rw-r--r-- 1 postgres postgres 4193826 Aug 31 2015 YIELD NAME.csv
-rw-r--r-- 1 postgres postgres 1665394 Sep 21 2015 CNF 2015 users_guide EN.pdf
-rw-r--r-- 1 postgres postgres 1637393 Sep 21 2015 CNF 2015 users_guide FR.pdf
-rw-r--r-- 1 postgres postgres 893270 Sep 21 2015 CNF 2015 Database structure EN .pdf
-rw-r--r-- 1 postgres postgres 972920 Sep 21 2015 CNF 2015 database structure FR .pdf
-rw-r--r-- 1 postgres postgres 50521 Oct 6 2015 MEASURE NAME.csv
-rw-r--r-- 1 postgres postgres 40265 Oct 9 2015 YIELD AMOUNT.csv
-rw-r--r-- 1 postgres postgres 16257583 Oct 30 2015 NUTRIENT AMOUNT.csv
但是,當我嘗試匯入時,在命令列上出現以下錯誤
2021-11-30 00:24:49.736 UTC [55] STATEMENT: copy cad.yield_name
from '/data/cad/base/YIELD\ NAME.csv'
delimiter ',' csv header;
psql:sql/postgres/cad/base/1_yield_name.sql:10: ERROR: could not open file "/data/cad/base/YIELD\ NAME.csv" for reading: No such file or directory
HINT: COPY FROM instructs the PostgreSQL server process to read a file. You may want a client-side facility such as psql's \copy.
我PostgreSQL 14.1在 Mac OSX 上使用docker 鏡像。有人可以幫助我了解如何使用copy命令匯入帶有空格的檔案名嗎?
謝謝
uj5u.com熱心網友回復:
問題 1:轉義檔案名中的空格。
雖然使用反斜杠
'\'來轉義空格' '是在 Unix/Linux shell 上在檔案名不加引號時完成的事情,但在 SQL 中沒有必要。- 在大多數(全部?)非 shell 腳本程式代碼中沒有必要,因為字串總是被分隔的(看著你,PowerShell)
- 另外,我注意到 MySQL 和 PostgreSQL 都支持反斜杠轉義,都不對空格字符使用反斜杠轉義。
- PostgreSQL 只識別
E''-style 字串中的反斜杠轉義序列,順便說一句。
- PostgreSQL 只識別
無論如何,只需洗掉反斜杠:
COPY cad.yield_name FROM '/data/cad/base/YIELD NAME.csv' DELIMITER ',' csv header;
問題二:檔案編碼
在評論回復中,您寫道您看到了此錯誤:
錯誤:編碼“UTF8”的位元組序列無效:0xE9 0x20 0x72
PostgreSQL 假設 CSV 檔案默認使用 UTF-8 編碼,但是字符序列
0xE9 0x20 0x72強烈暗示檔案具有 ISO-8859-1 編碼。- 這種編碼現在有點過時了 - 你應該提示制作它的人改用 UTF-8。
所以添加
ENCODING引數:COPY cad.yield_name FROM '/data/cad/base/YIELD NAME.csv' DELIMITER ',' csv header ENCODING 'ISO 8859-1';
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/372818.html
標籤:sql 数据库 PostgreSQL的 文件
下一篇:讓查找回傳多行多列的陣列
