pg_dump和pg_restore的使用

pg_dump是用于postgresql数据备份的工具。即使数据库在并发的情况下也能保持一致性,并且不阻塞其它用户对数据库进行读和写。

将表account和host表中数据dump到szd.dump文件中
pg_dump -n 'public'  -Uroot --no-owner --no-privileges --host=100.2.2.1 --port=5432 --disable-triggers -d szd -t account -t host > szd.dump

将数据恢复到指定的数据库中
pg_restore -n 'public' -Uroot --no-owner --host=100.2.2.3 --port=6434 -t account -t host szd.dump

但是发再使用上述命令备份的并不包含索引,查看文档未发现可以恢复索引的选项。经实战发现如下方法可以备份索引,
1.通过pg_dump备份表的结构信息,
2.通过psql恢复表结构,
3.最后通过pg_restore恢复数据。

1.备份表结构信息
pg_dump -n 'public'  -Uroot --no-owner --schema-only --no-privileges --host=100.2.2.1 --port=5432 --disable-triggers -d szd -t account -t host > szd2.dump

2.恢复表结构信息以及索引
psql -h100.2.2.3 -p6434 -Uroot szd < szd2.dump

3.恢复数据
pg_restore -n 'public' -Uroot --no-owner --data-only --host=100.2.2.3 --port=6434 -t account -t host szd.dump

create database ptldwh template template0; #To make an empty database without any local additions


pg_dump -Fc -v -n 'public' --host=127.0.0.1 -p5433 --no-owner --no-privileges --username=ptldwhdata ptldwh -t host >ptldwh.dump

-t 't_*' #指定要同步的表名

pg_restore -n 'public' -Uroot --no-owner --no-privileges --disable-triggers -d ptldwh -t host ptldwh.dump

常用参数

参数 描述
-n schema 指定schema,只备份schema下的数据
—data-only 只备份数据
—format=format 指定输出格式
-N schema 不备份此schema下的数据
—no-owner 不输出设置对象ownership的命令
—schema-only 只备份表结构信息
-t table 指定需要备份的表
-T table 不备份此表

Ref:
1.pg_dump
2.pg_restore