备份 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