权限

copy 必须要以超级用户来运行

\copy 则不必

文件位置

copy 的文件必须是在服务器端的位置

\copy 的则是在客户端的位置。

所以,文件的权限方面,copy是以服务器的为准,\copy 是以客户端的为准

例子

DB服务器:10.0.0.10

postgres=# \du yang;
           List of roles
 Role name | Attributes | Member of 
-----------+------------+-----------
 yang      |            | {}

postgres=# 

客户端(10.0.0.11)连接到DB服务器(10.0.0.10) 客户端运行copy命令(11):

/tmp/tcopy.txt该文件是在客户端(10.0.0.11)的,DB服务器(10.0.0.10)并不存在该文件。

test=> copy tcopy from '/tmp/tcopy.txt';
ERROR:  must be superuser to COPY to or from a file
HINT:  Anyone can COPY to stdout or from stdin. psql's \copy command also works for anyone.
test=> 

它会报告必须要以数据库的超级用户身份才能运行copy命令。

客户端运行\copy命令(11):

test=> \copy tcopy from '/tmp/tcopy.txt';
COPY 3
test=> 

它没有报告必须要以数据库的超级用户来运行,而且也没有报告文件或目录不存在的问题。

在DB(10.0.0.10)服务器端修改用户yang为超级用户:

postgres=# alter role yang superuser ;
ALTER ROLE
postgres=# 

然后在客户端再执行看看:

test=> copy tcopy from '/tmp/tcopy.txt';
ERROR:  could not open file "/tmp/tcopy.txt" for reading: No such file or directory
test=> 

它现在不报权限了,而是报告文件或目录不存在。这是因为该文件是在客户端的,而copy只会在服务器端定位。

在客户端换成\copy命令看看:

test=> \copy tcopy from '/tmp/tcopy.txt';
COPY 3
test=> 

可以发现COPY成功了。