做者:瀚高PG實驗室 (Highgo PG Lab)- 禹曉git
本文主要用於介紹如何使用copy或者\copy命令將postgresql數據庫內表的數據導出爲excel格式,方便用戶查看編輯。sql
copy命令同\copy命令語法上相同,區別在於copy必須使用可以超級用戶使用,copy … to file 中的文件都是數據庫服務器所在的服務器上的文件,而\copy 通常用戶便可執行且\copy 保存或者讀取的文件是在客戶端所在的服務器。本文主要以copy命令做爲介紹重點,使用copy命令將表內數據倒爲csv格式文件即爲excel格式。
一、copy命令語法數據庫
COPY { 表名 [ ( 列名稱 [, ...] ) ] | ( 查詢 ) } TO { '文件名' | PROGRAM '命令' | STDOUT } [ [ WITH ] ( 選項 [, ...] ) ]選項能夠是下列內容之一 FORMAT 格式_名稱 FREEZE [ 布爾 ] DELIMITER '分隔字符' NULL '空字符串' HEADER [ 布爾 ] QUOTE '引用字符' ESCAPE '轉義字符' FORCE_QUOTE { ( 列名稱 [, ...] ) | * } FORCE_NOT_NULL ( 列名稱 [, ...] ) FORCE_NULL ( 列名稱 [, ...] ) ENCODING 'encoding_name(編碼名)'
二、多場景使用介紹
①查看現有表數據服務器
test=# select * from test;user_id | user_name | age | gender | remark ---------+---------------+-----+--------+---------------------------------------------- 1 | Jackie Chan | 45 | male | "police story","project A","rush hour" 3 | Brigitte Li | 46 | female | 4 | Maggie Cheung | 39 | female | 5 | Jet Li | 41 | male | "Fist of Legend","Once Upon a Time in China" 2 | Gong Li | 38 | female | "Farewell My Concubine","Lifetimes Living"(5 行記錄)
②帶列名導出,默認狀況下使用,做爲分隔符ide
test=# copy test to '/tmp/test1.csv' with csv header;COPY 5test=# \! cat /tmp/test1.csvuser_id,user_name,age,gender,remark1,Jackie Chan,45,male,"""police story"",""project A"",""rush hour"""3,Brigitte Li,46,female,4,Maggie Cheung,39,female,5,Jet Li,41,male,"""Fist of Legend"",""Once Upon a Time in China"""2,Gong Li,38,female,"""Farewell My Concubine"",""Lifetimes Living"
③帶列名導出,指定使用|做爲分隔符post
test=# copy test to '/tmp/test1.csv' with csv header DELIMITER '|';COPY 5test=# \! cat /tmp/test1.csvuser_id|user_name|age|gender|remark1|Jackie Chan|45|male|"""police story"",""project A"",""rush hour"""3|Brigitte Li|46|female|4|Maggie Cheung|39|female|5|Jet Li|41|male|"""Fist of Legend"",""Once Upon a Time in China"""2|Gong Li|38|female|"""Farewell My Concubine"",""Lifetimes Living"
④帶列名導出,將空字符替換爲指定值導出編碼
test=# copy test to '/tmp/test1.csv' with csv header null 'to be supplemented';COPY 5test=# \! cat /tmp/test1.csvuser_id,user_name,age,gender,remark1,Jackie Chan,45,male,"""police story"",""project A"",""rush hour"""3,Brigitte Li,46,female,to be supplemented4,Maggie Cheung,39,female,to be supplemented5,Jet Li,41,male,"""Fist of Legend"",""Once Upon a Time in China"""2,Gong Li,38,female,"""Farewell My Concubine"",""Lifetimes Living"