加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

copy命令介绍

发布时间:2020-12-13 17:25:25 所属栏目:百科 来源:网络整理
导读:COPY 命令可以快速的导入数据到 postgresql 数据库中,文件格式类似 TXT 、 CVS 之类。适合批量导入数据,速度比较快。注意 COPY 只能用于表,不能用于视图。 COPY 命令里面的文件必须是由服务器直接读或写的文件,而不是由客户端应用读写。 因此,它们必须

COPY 命令可以快速的导入数据到postgresql数据库中,文件格式类似TXTCVS之类。适合批量导入数据,速度比较快。注意COPY只能用于表,不能用于视图。

COPY命令里面的文件必须是由服务器直接读或写的文件,而不是由客户端应用读写。因此,它们必须位于数据库服务器上或者可以为数据库服务器所访问,而不是由客户端做这些事情。它们必须是PostgresqlSQL用户(服务器运行的用户 ID)可以访问到并且可读或者可写,而不是客户端。COPY到一个命名文件是只允许数据库超级用户进行的,因为它允许读写任意服务器有权限访问的文件。

导入文件或者 STDIN到表中

导出表数据到文件或 STDOUT

copy命令可以操作的文件类型有:txt、sql、csv、压缩文件、二进制格式

1、 copy命令导入数据示例:tb2是表名,delimiter ',' 表示按逗号分隔字段数据

postgresql=# copy tb2 from '/mnt/postgresql/weibo.1000'delimiter ',';

COPY1000

postgresql=# select count(*)from tb2;

count

-------

1000

(1 row)

2、 copy命令导入导出数据为sql格式

postgresql=# COPY tb2 TO '/mnt/postgresql/weibo.sql';

COPY1000

postgresql=# COPY tb2 from '/mnt/postgresql/weibo.sql';

COPY2000

3、 copy命令导出指定字段数据在控制台

postgresql=# COPY tb2 (t1,t2,t3)TOSTDOUT;

21317568596 1270505818

21317568149 2302617224

21317568470 1297983318

21317568110 2069993004 2302781822

21317568354 362106137

21317568308 1450475836

21317568584 83103917

21317568208 1844532765 1713926427

21317568603 1227221083 2478474742

21317568151 1430992492 1253397461

21317567390 1037539510

4、copy命令导入导出数据为csv格式

postgresql=# COPY tb2 (t1,t3)TO '/mnt/postgresql/weibo.csv' CSV HEADER;

COPY2000

postgresql=# COPY tb2 from '/mnt/postgresql/weibo1.csv';

COPY2000

5、 copy命令导入导出数据为txt格式

postgresql=# COPY tb2 TO '/mnt/postgresql/weibo.txt';

COPY2000

postgresql=# COPY tb2 from '/mnt/postgresql/weibo.txt';

COPY2000

6、 copy命令导出数据为压缩文件

postgresql=# COPY tb2 TOPROGRAM 'gzip >/mnt/postgresql/weibo.1000.gz';

COPY2000

7、 copy命令导入导出文件为二进制

用copyto命令以二进制形式把tb2表的内容拷贝到binary文件中

postgresql=# copy binary tb2 to'/mnt/postgresql/binary';

COPY 8000

用copyfrom命令把binary文件中的数据拷贝到表从tb2中

postgresql=# copy binary tb2 from'/mnt/postgresql/binary';

COPY 8000

7、excel表中的数据导入到Postgresql数据库的某张表中。

步骤:

1.excel表格字段,按照postgresql数据库中表的字段顺序来整理数据,并保存为csv文件。

2.用记事本打开csv文件,另存为UTF-8格式。

3.使用客户端链接postgresql数据库,执行如下脚本,导入csv文件到Postgresql数据表:

copytestdatafrom 'd:/test/testdata.csv' delimiter as',' csv quote as '"'

注:testdatapostgresql数据库表的名称。

注意事项:

1.test目录需要赋予postgresql用户可读写的权限,否则会有如下报错信息:

ERROR: could not open file "d:/testdata2.csv" forwriting:Permission denied

2.csv文件要为utf-8格式,否则导入时可能会有报错:

ERROR:invalid bytesequence for encoding "UTF8": 0xcdf5

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读