📅  最后修改于: 2023-12-03 15:03:48.978000             🧑  作者: Mango
在 PostgreSQL 中,COPY 命令被用于将表或查询的结果输出到文件或从文件中导入数据到表中。如果需要对数据进行复制或备份,COPY 命令可以是非常有用的工具。在本文中,我们将阐述 COPY 命令的详细语法和用法。
复制表的语法如下:
COPY table_name [(column_list)]
TO { 'filename' | STDOUT }
[ [ WITH ] [ BINARY | CSV | DELIMITER [ AS ] 'delimiter' ] ]
[ HEADER ]
[ ENCODING 'encoding' ]
[ FREEZE ]
COPY table_name [(column_list)]
FROM { 'filename' | STDIN }
[ [ WITH ] [ BINARY | CSV | DELIMITER [ AS ] 'delimiter' ] [ QUOTE [ AS ] 'quote' ] [ ESCAPE [ AS ] 'escape' ] ]
[ HEADER [ boolean ] ]
[ FORMAT { 'csv' | 'text' | 'custom' }
[ DELIMITER 'delimiter' ]
[ NULL 'null string' ]
[ ESCAPE 'escape character' ]
[ ENCODING 'encoding' ]
[ FORCE_QUOTE { ALL | numeric... } ]
[ FORCE_NOT_NULL ( column_name [, ...] ) ]
[ HEADER ]
[ QUOTE 'quote character' ]
[ RECORD_DELIMITER 'record delimiter' ]
[ WITH option [ ... ] ] ]
[ OIDS [ boolean ] ]
复制查询的语法如下:
COPY (query)
TO { 'filename' | STDOUT }
[ [ WITH ] [ BINARY | CSV | DELIMITER [ AS ] 'delimiter' ] ]
[ HEADER ]
[ ENCODING 'encoding' ]
[ FREEZE ]
COPY (query)
FROM { 'filename' | STDIN }
[ [ WITH ] [ BINARY | CSV | DELIMITER [ AS ] 'delimiter' ] [ QUOTE [ AS ] 'quote' ] [ ESCAPE [ AS ] 'escape' ] ]
[ HEADER [ boolean ] ]
[ FORMAT { 'csv' | 'text' | 'custom' }
[ DELIMITER 'delimiter' ]
[ NULL 'null string' ]
[ ESCAPE 'escape character' ]
[ ENCODING 'encoding' ]
[ FORCE_QUOTE { ALL | numeric... } ]
[ FORCE_NOT_NULL ( column_name [, ...] ) ]
[ HEADER ]
[ QUOTE 'quote character' ]
[ RECORD_DELIMITER 'record delimiter' ]
[ WITH option [ ... ] ] ]
[ OIDS [ boolean ] ]
table_name
: 要复制的表名。column_list
: 要复制的列名列表。filename
: 目标文件名或标准输出流。query
: 要执行的查询。BINARY
: 用于以二进制模式转储数据的参数。CSV
: 以 CSV 格式保存数据。DELIMITER
: 指定分隔符。ENCODING
: 指定编码方案。FREEZE
: 冻结输出。FORMAT
: 以指定的格式存储数据。HEADER
: 包括标题行。NULL
: 指定 NULL 字符串。QUOTE
: 指定引用符号。RECORD_DELIMITER
: 指定记录分隔符。WITH
: 用于指定其他参数。以下示例将从表中导出数据到 CSV 文件中:
COPY products TO '/tmp/products.csv' CSV HEADER;
以下示例从 CSV 文件中导入数据到表中:
COPY products FROM '/tmp/products.csv' CSV HEADER;
以下示例将查询结果导出到 CSV 文件中:
COPY (SELECT * FROM products WHERE price > 100) TO '/tmp/expensive_products.csv' CSV HEADER;
COPY 命令使得快速复制和备份数据变得非常容易。在使用 COPY 命令时,需要了解其语法和参数选项,以充分利用其功能。