[完整版]Postgresql 数据库 备份以及恢复的过程

时间:2023-03-09 15:45:04
[完整版]Postgresql 数据库 备份以及恢复的过程

0. 准备工作

linux机器上面 必须安装上pg数据库
然后 需要将 pg的主程序目录 放到环境变量里面去 便于执行命令.

1. 先备份

. 备份目标数据库:
pg_dump -h 10.24.193.25 -U postgres -p -F c -f /TestPG/TestDS0816.dmp TestDS0816
# -h 小写 指向目标服务器
# -U 大写 使用的用户
# -p 小写 pg 数据库使用的端口.
# -F 指代导出格式. c 只的就是 自定义的pg_dump格式.
# -f 指代目录
# 目标数据库在最后面. man的内容为:
-F format
--format=format
Selects the format of the output. format can be one of the following: p
plain
Output a plain-text SQL script file (the default). c
custom
Output a custom-format archive suitable for input into pg_restore. Together with the directory output format, this is the most flexible output format in that it allows manual selection and reordering of archived items during restore. This format is
also compressed by default. d
directory
Output a directory-format archive suitable for input into pg_restore. This will create a directory with one file for each table and blob being dumped, plus a so-called Table of Contents file describing the dumped objects in a machine-readable
format that pg_restore can read. A directory format archive can be manipulated with standard Unix tools; for example, files in an uncompressed archive can be compressed with the gzip tool. This format is compressed by default and also supports
parallel dumps. t
tar
Output a tar-format archive suitable for input into pg_restore. The tar format is compatible with the directory format: extracting a tar-format archive produces a valid directory-format archive. However, the tar format does not support compression.
Also, when using tar format the relative order of table data items cannot be changed during restore.

2. 创建用户以及创建数据库

登录数据库

 psql -U postgres

创建用户以及创建数据库 注意 这里面有很大的一个坑  创建的时候 不区分大小写 ,但是因为恢复的区分大小写,所以必须添加 "" 双引号括住 数据库和用户的名字才可以.
(感谢平台部 刘威 协助..这一块坑了我半个多小时.) 创建用户
create role "TestDS0816" superuser login;
创建数据库
create database "TestDS0816" ;
设置密码
alter role "TestDS0816" with password 'Test6530';
退出数据库的命令为:
\q

3.执行恢复

pg_restore -U postgres -d TestDS0816 /TestPG/TestDS0816.dmp
# -U 大写 用户
# -d 小写指代目标.