COPY命令:为PostgreSQL批量导入数据

前端之家收集整理的这篇文章主要介绍了COPY命令:为PostgreSQL批量导入数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

任务:将excel表中的数据导入到Postgresql数据库的某张表中。

工具:Postgresql客户端pgAdmin。

步骤:

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

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

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

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

注:testdata 是postgresql数据库表的名称

注意事项:

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

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

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

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

3.注意windows环境下文件路径的表述方式,如:d:/test/data.csv

附录:

1.postgresql数据表也可以批量导出为csv格式,命令如下:

copy testdata to 'd:/test/testdata.csv' delimiteras ',' csv quote as '"'

2.copy 命令的其他用法

COPY--在表和文件之间拷贝数据

(1)COPY FROM

COPY tablename [ ( column [,...] ) ]
FROM {'filename' | STDIN }
[ [ WITH]
[ BINARY ]
[ OIDS ]
[ DELIMITER [ AS ] 'delimiter']
[ NULL [ AS ] 'null string']
[ CSV [ HEADER ]
[ QUOTE [ AS ] 'quote' ]
[ ESCAPE [ AS ] 'escape']
[ FORCE NOT NULL column [,...]]
(2)COPY TO

COPY tablename [ (column [,...] ) ]
TO {'filename' | STDOUT }

[ [ WITH ]

[ BINARY ]

[ OIDS ]

[ DELIMITER [ AS ] 'delimiter']
[ NULL [ AS ] 'null string']
[ CSV [ QUOTE [ AS ] 'quote']
[ ESCAPE [ AS ] 'escape']
[ FORCE QUOTE column [,...]]
参数详细说明见:Postgresql 8.1 中文文档,http://www.pgsqldb.org/pgsqldoc-8.1c/sql-copy.html

原文链接:https://www.f2er.com/postgresql/195954.html

猜你在找的Postgre SQL相关文章