PostgreSQL 数据库的备份

一、建立数据库连接

命令:

psql -h IP地址 -p 端口 -U 数据库用户名 -d 数据库名
psql -h 127.0.0.1 -p 5432 -U postgres -d postgres

psql命令连接选项

Connection options:

  -h, --host=HOSTNAME     主机   默认local
  -p, --port=PORT         端口   默认5432
  -U, --username=USERNAME 用户名 默认postgres
  -w, --no-password       从不提示密码
  -W, --password          强制 psql 提示输入密码,即使没有密码也会提示。
  -d                 指定要连接的库名

=============================================

二、数据备份还原

pg_restore可以恢复由pg_dump备份的文件,它会重新生成包括数据在内的所有用户定义的类型、函数、表、索引的所有别要的命令
使用-d选项执行数据库的名称,-C指定备份文件的路径

pg_restore -d testdb -U postgres -C /home/postgres/testdb.sql

psql是一个PostgreSQL的终端,它可以运行用户输入的语句,输入的语句还可以来自一个文件,

所以对于备份的包含create、insert语句的文本文件,可以使用psql恢复到数据中。

psql -d  testdb -U postgres -f /home/postgres/testdb.sql 

1. pg_dump备份数据库

命令:pg_dump -h IP地址 -p 端口 -U 数据库用户名 -f 目标存储文件及路径 目标数据库名

备份testdb数据库到/home/postgres/testdb.sql文件

pg_dump  -U postgres -f /home/postgres/testdb.sql testdb

恢复

psql  -U postgres -d testdb -f /home/postgres/testdb.sql 

备份testdb库中的pmp_login_log表

pg_dump -U postgres -t pmp_login_log -f /home/postgres/login_log.sql testdb

恢复

psql  -U postgres -d testdb -f /home/postgres/login_log.sql

2. pg_dumpall备份数据库

使用pg_dumpall备份整个服务器的数据库

备份

pg_dumpall -U postgres -f /home/postgres/postgres.sql

恢复

psql -U postgres -f /home/postgres/postgres.sql

三、PostgreSQL 无须手动输入密码

PostgreSQL里没有加入密码选项,一般备份命令需要手动输入密码,所以会给自动备份带来一定的不便。

查看了官方文档,(英文不好,全程都翻译/(ㄒoㄒ)/~~)

PGPASSWORD behaves the same as the password connection parameter. Use of this environment variable is not recommended for security reasons, as some operating systems allow non-root users to see process environment variables via ps; instead consider using the ~/.pgpass file (see Section 32.15).

PGPASSFILE specifies the name of the password file to use for lookups. If not set, it defaults to ~/.pgpass (see Section 32.15).

On Unix systems, the permissions on.pgpassmust disallow any access to world or group; achieve this by the command chmod 0600 ~/.pgpass. If the permissions are less strict than this, the file will be ignored. 

文档中提到两种方法;

第一种方法:通过PostgreSQL的环境变量参数来实现保存密码。

export

第二种方法:创建 ~/.pgpass 文件来保存密码

密码文件的格式: hostname:port:database:username:password

cat ~/.pgpass 
localhost:5432:testdb:postgres:123456

注意:

根据官方文档的说明,因为安全的原因,不推荐环境变量的方式,推荐使用~/.pgpass 来保存密码,此文件必须设置0600权限,如果权限不那么严格,则该文件将被忽略。

chmod 0600 ~/.pgpass
标签:备份PostgreSQL 发布于:2019-11-04 02:41:08