COPY 命令可以快速的導入數據到postgresql數據庫中,文件格式類似TXT、CVS之類。適合批量導入數據,速度比較快。注意COPY只能用於表,不能用於視圖。
COPY 命令里面的文件必須是由服務器直接讀或寫的文件,而不是由客戶端應用讀寫。因此,它們必須位於數據庫服務器上或者可以為數據庫服務器所訪問,而不是由客戶端做這些事情。它們必須是PostgresqlSQL用戶(服務器運行的用戶 ID)可以訪問到並且可讀或者可寫,而不是客戶端。 COPY 到一個命名文件是只允許數據庫超級用戶進行的,因為它允許讀寫任意服務器有權限訪問的文件。
導出表數據到文件或 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)
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) TO STDOUT; 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,t2,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數據表:
copy testdatafrom 'd:/test/testdata.csv' delimiter as',' csv quote as '"'
注:testdata是postgresql數據庫表的名稱。
注意事項:
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