備份 PG 數據庫生成的文件能夠有兩種,一種是 SQL 文件,一種是二進制文件,二進制文件只能使用 pg_restore 進行恢復。html
PostgreSQL 數據庫操做簡要說明linux
PostgreSQL數據庫版本sql
psql --version
psql (PostgreSQL) 9.1.3數據庫
下面是在linux下的操做,在windows下面將su -postgres 換爲windows
運行輸入cmd→d:→數據結構
cd D:\Program Files\PostgreSQL\9.2\bin,下面建立表、刪除表時,須要在postgres下操做,所以須要在建立刪除數據庫前面輸入psql -u postgresapp
1、數據庫備份post
一、備份數據庫結構rest
su - postgres
pg_dump -Fc -s -f testdbschema.sql testdbpostgresql
二、備份數據庫數據
su - postgres
pg_dump -Fc -a -f testdbdata.sql testdb
三、備份數據庫結構和數據
su - postgres
pg_dump -Fc -f testdbschemadata.sql testdb
四、備份數據庫中指定表結構
pg_dump -Fc -s -t citycode -f citycode_schema.sql testdb
五、備份數據庫中指定表數據
pg_dump -Fc -a -t citycode -f citycode_data.sql testdb
.六、備份數據庫中指定表(結構和數據)
pg_dump -Fc -t citycode -f citycode_schemadata.sql testdb
2、刪除數據庫
su - postgres
dropdb testdb
3、恢復數據庫
一、建立新數據庫testdb
su - postgres
createdb testdb;
二、 恢復數據結構(only schema)
su - postgres
pg_restore -s -d testdb testdbschema.sql
三、恢復數據庫數據(only data)
su - postgres
pg_restore -a -d testdb testdbdata.sql
四、恢復數據庫結構和數據(schema and data)
su - postgres
pg_restore -d testdb testdbschemadata.sql
五、指定表數據恢復
1)刪除表
psql testdb
DROP TABLE citycode;
2)恢復表結構
pg_restore -s -t citycode -d testdb citycode_schema.sql
3)恢復表數據
pg_restore -a -t citycode -d testdb citycode_data.sql
4)恢復表(結構和數據)
pg_restore -t citycode -d testdb citycode_schemadata.sql
以上備份恢復相關操做可用於靜態(無數據增加)數據庫。
重要提示:pg_restore 可用來恢復pg_dump命令以 (Fc\Ft)格式備份的數據文件。執行pg_dump備份命令時若無此格式參數聲明,pg_restore 恢復時可能出現錯誤提示「pg_restore: [archiver] input file does not appear to be a valid archive」。
pg_dump 官方文檔
https://www.postgresql.org/docs/10/app-pgdump.html
pg_dumpall
https://www.postgresql.org/docs/10/app-pg-dumpall.html
pg_restore