You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将PostgreSQL备份恢复至指定的替代数据库名称?

Postgres pg_restore 指定目标库仍恢复到原库的解决办法

问题原因

你用到的-C(--create)参数是核心问题:

  • 当使用-C时,pg_restore会读取备份里的原数据库元数据(也就是你备份的postgres库),先执行CREATE DATABASE postgres(如果不存在),然后自动切换到这个库完成数据恢复。
  • 此时你指定的--dbname=restore只是初始连接用的数据库(用来执行创建数据库的命令),并不是最终的恢复目标库。

解决方案

方案一:移除-C参数(推荐)

这个方法最简单,前提是你已经提前创建好目标库restore:

  1. 先创建目标库:
createdb -h $pghost -U $username restore
  1. 执行恢复命令(去掉-C):
pg_restore -Fd -j 4 --schema=public --no-owner --verbose --host=$pghost --username=$username --dbname=restore $filename

方案二:保留-C但修改备份中的数据库名

如果必须用-C参数(比如需要自动创建库),需要修改备份里的数据库名称:

  1. 导出备份的目录列表到文件:
pg_restore -Fd --list $filename > restore_list.txt
  1. 编辑restore_list.txt,找到包含CREATE DATABASE postgres的行,把postgres改成restore。
  2. 执行恢复命令(用--use-list指定修改后的列表,--dbname填一个已存在的库比如postgres,用来初始连接):
pg_restore -Fd -C -j 4 --schema=public --no-owner --verbose --host=$pghost --username=$username --dbname=postgres --use-list=restore_list.txt $filename

注意事项

  • directory格式的备份包含完整的数据库元数据,-C参数会优先使用备份里的原库名,所以必须通过上述两种方式调整。
  • 确保执行命令的用户有足够权限:创建数据库、读写目标库的权限。

内容的提问来源于stack exchange,提问作者Gregory Suvalian

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 12:10:29