域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過(guò)
本文主要用于介紹如何使用copy或者\(yùn)copy命令將postgresql數(shù)據(jù)庫(kù)內(nèi)表的數(shù)據(jù)導(dǎo)出為excel格式,方便用戶查看編輯。
copy命令同\copy命令語(yǔ)法上相同,區(qū)別在于copy必須使用能夠超級(jí)用戶使用,copy … to file 中的文件都是數(shù)據(jù)庫(kù)服務(wù)器所在的服務(wù)器上的文件,而\copy 一般用戶即可執(zhí)行且\copy 保存或者讀取的文件是在客戶端所在的服務(wù)器。本文主要以copy命令作為介紹重點(diǎn),使用copy命令將表內(nèi)數(shù)據(jù)倒為csv格式文件即為excel格式。
1、copy命令語(yǔ)法
COPY { 表名 [ ( 列名稱 [, ...] ) ] | ( 查詢 ) }
TO { '文件名' | PROGRAM '命令' | STDOUT }
[ [ WITH ] ( 選項(xiàng) [, ...] ) ]
選項(xiàng)可以是下列內(nèi)容之一
FORMAT 格式_名稱
FREEZE [ 布爾 ]
DELIMITER '分隔字符'
NULL '空字符串'
HEADER [ 布爾 ]
QUOTE '引用字符'
ESCAPE '轉(zhuǎn)義字符'
FORCE_QUOTE { ( 列名稱 [, ...] ) | * }
FORCE_NOT_NULL ( 列名稱 [, ...] )
FORCE_NULL ( 列名稱 [, ...] )
ENCODING 'encoding_name(編碼名)'
2、多場(chǎng)景使用介紹
①查看現(xiàn)有表數(shù)據(jù)
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 行記錄)
②帶列名導(dǎo)出,默認(rèn)情況下使用,作為分隔符
test=# copy test to '/tmp/test1.csv' with csv header;
COPY 5
test=# \! cat /tmp/test1.csv
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"
③帶列名導(dǎo)出,指定使用|作為分隔符
test=# copy test to '/tmp/test1.csv' with csv header DELIMITER '|';
COPY 5
test=# \! cat /tmp/test1.csv
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"
④帶列名導(dǎo)出,將空字符替換為指定值導(dǎo)出
test=# copy test to '/tmp/test1.csv' with csv header null 'to be supplemented';
COPY 5
test=# \! cat /tmp/test1.csv
user_id,user_name,age,gender,remark
1,Jackie Chan,45,male,"""police story"",""project A"",""rush hour"""
3,Brigitte Li,46,female,to be supplemented
4,Maggie Cheung,39,female,to be supplemented
5,Jet Li,41,male,"""Fist of Legend"",""Once Upon a Time in China"""
2,Gong Li,38,female,"""Farewell My Concubine"",""Lifetimes Living"
文章來(lái)源:腳本之家
來(lái)源地址:https://www.jb51.net/article/206930.htm
申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!