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 PGPASSWORD="123456"
第二种方法:创建 ~/.pgpass 文件来保存密码
密码文件的格式: hostname:port:database:username:password
cat ~/.pgpass
localhost:5432:testdb:postgres:123456
注意:根据官方文档的说明,因为安全的原因,不推荐环境变量的方式,
推荐使用~/.pgpass 来保存密码,此文件必须设置0600权限,如果权限不那么严格,则该文件将被忽略。
chmod 0600 ~/.pgpass
运维网声明
1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网 享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com