Postgresql

在命令行上執行 COPY 命令時如何轉義字元?

  • December 12, 2021

我在 CentOS 7 上使用 Postgres 14。我想從 bash 腳本執行複制命令。我首先嘗試在命令行上執行命令

$ PGPASSWORD=$DB_PASS psql -U $DB_USER -d $DB_NAME -c 'COPY myapp_currencyprice to STDOUT WITH (DELIMITER ",", FORMAT CSV, HEADER) \g /tmp/prices.csv'
ERROR:  syntax error at or near "\"
LINE 1: ...o STDOUT WITH (DELIMITER ",", FORMAT CSV, HEADER) \g /tmp/pr...

逃避分隔符的正確方法是什麼?我試過改變我的單引號和雙引號,但無濟於事。

psql的-c選項不支持混合使用 SQL 命令和元命令。並且由於這是\g可以合理使用的唯一方法,\g因此不支持該方法-c

不過,也不乏其他選擇。

psql -c 'COPY myapp_currencyprice to STDOUT WITH (DELIMITER ",", FORMAT CSV, HEADER)' > /tmp/prices.csv

psql -c '\COPY myapp_currencyprice to /tmp/prices.csv WITH (DELIMITER ",", FORMAT CSV, HEADER)'

psql -f <(echo 'COPY myapp_currencyprice to STDOUT WITH (DELIMITER ",", FORMAT CSV, HEADER) \g /tmp/prices.csv')

psql <<END
COPY myapp_currencyprice to STDOUT WITH (DELIMITER ",", FORMAT CSV, HEADER) \g /tmp/prices.csv
END

引用自:https://dba.stackexchange.com/questions/303830