PostgreSQL 数据库备份与恢复 pd_dump pg_restore

时间:2022-01-10 02:44:41

备份 PG 数据库生成的文件可以有两种,一种是 SQL 文件,一种是二进制文件,二进制文件只能使用 pg_restore 进行恢复。

 

PostgreSQL 数据库操作简要说明

PostgreSQL数据库版本

psql --version
psql (PostgreSQL) 9.1.3

 

下面是在linux下的操作,在windows下面将su -postgres 换为

运行输入cmd→d:→

cd D:\Program Files\PostgreSQL\9.2\bin,下面创建表、删除表时,需要在postgres下操作,因此需要在创建删除数据库前面输入psql -u postgres

一、数据库备份

1、备份数据库结构

su - postgres
pg_dump -Fc -s -f testdbschema.sql testdb

2、备份数据库数据

su - postgres
pg_dump -Fc -a -f testdbdata.sql testdb

3、备份数据库结构和数据

su - postgres
pg_dump -Fc -f testdbschemadata.sql testdb

4、备份数据库中指定表结构

 pg_dump -Fc -s -t citycode -f citycode_schema.sql testdb

5、备份数据库中指定表数据

 pg_dump -Fc -a -t citycode -f citycode_data.sql testdb

.6、备份数据库中指定表(结构和数据)

 pg_dump -Fc -t citycode -f citycode_schemadata.sql testdb

二、删除数据库

su - postgres

dropdb testdb

三、恢复数据库

1、创建新数据库testdb

su - postgres

createdb testdb;


2、 恢复数据结构(only schema)

su - postgres

 pg_restore -s -d testdb testdbschema.sql 
 

3、恢复数据库数据(only data)

su - postgres

pg_restore -a -d testdb testdbdata.sql

4、恢复数据库结构和数据(schema and data)

su - postgres

pg_restore -d testdb testdbschemadata.sql

5、指定表数据恢复

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

https://www.postgresql.org/docs/10/app-pgrestore.html