在本地,我使用pgadmin3。然而,在远程服务器上,我没有这样的特权。
我已经创建了数据库备份并复制了它,但是是否有一种方法可以从命令行恢复备份?我只看到与GUI或pg_dumps相关的东西。
在本地,我使用pgadmin3。然而,在远程服务器上,我没有这样的特权。
我已经创建了数据库备份并复制了它,但是是否有一种方法可以从命令行恢复备份?我只看到与GUI或pg_dumps相关的东西。
当前回答
恢复postgres备份文件取决于最初是如何进行备份的。
如果你使用pg_dump和-F c或-F d,你需要使用pg_restore,否则你可以使用
psql -h localhost -p 5432 -U postgres <备份文件
9种备份和恢复postgres数据库的方法
其他回答
根据创建转储文件的方式,有两个工具可供参考。
您的第一个引用源应该是手册页pg_dump,因为它创建了转储本身。它说:
Dumps can be output in script or archive file formats. Script dumps are plain-text files containing the SQL commands required to reconstruct the database to the state it was in at the time it was saved. To restore from such a script, feed it to psql(1). Script files can be used to reconstruct the database even on other machines and other architectures; with some modifications even on other SQL database products. The alternative archive file formats must be used with pg_restore(1) to rebuild the database. They allow pg_restore to be selective about what is restored, or even to reorder the items prior to being restored. The archive file formats are designed to be portable across architectures.
所以这取决于它被倾倒的方式。如果使用Linux/Unix,您可能可以使用excellent file(1)命令来找出它-如果它提到ASCII文本和/或SQL,它应该用psql恢复,否则您可能应该使用pg_restore。
恢复非常简单:
psql -U username -d dbname < filename.sql
-- For Postgres versions 9.0 or earlier
psql -U username -d dbname -1 -f filename.sql
or
pg_restore -U username -d dbname -1 filename.dump
查看它们各自的手册页-有相当多的选项会影响恢复的工作方式。在恢复之前,您可能必须清除“活动”数据库或从template0重新创建它们(正如评论中指出的那样),这取决于转储是如何生成的。
此解决方案仅适用于Windows。
首先,确保您已经将postgres bin文件夹添加到“Path”环境变量中(在我的例子中,这个文件夹是C:\Program Files\PostgreSQL\12\ bin)。
然后,打开Windows命令解释器(cmd),进入.sql文件所在的文件夹并执行以下命令:
pg_restore -U userName -d database-1 backupfile.sql
例如:
pg_restore -U sam -d SamDataBase -1 SamDataBaseBackup.sql
(它会问你的用户密码,所以确保输入正确,然后点击enter)
普拉维达!
使用压缩转储保存和恢复完全相同的状态
其他答案分别给出了所有的关键位,但希望这将提供“只是工作保存和恢复到精确状态”的命令对。
转储到文件mydb.psql:
PGPASSWORD=mypassword pg_dump -U my_username -h localhost mydb -Fc -f mydb.psql
恢复:
PGPASSWORD=mypassword pg_restore -U my_username -h localhost \
--clean -d mydb -v mydb.psql
一些旗帜:
-Fc:格式压缩,而不是明文。 tmp文件。psql说: tmp。psql: PostgreSQL自定义数据库转储- v1.14-0 ——clean:在恢复目标DB之前销毁它,从而返回到完全相同的原始状态。 转储之后创建的任何数据都将丢失。
PGPASSWORD, -U和-h当然可以根据您的登录方法进行修改,例如,如果没有PGPASSWORD,您将提示输入密码,如果您在本地设置peer auth,这些都不需要。
在Ubuntu 22.04和PostgreSQL 14.5上测试。
备份= = >
选项1:在cmd中备份密码 1.PGPASSWORD="mypassword" pg_dump -U postgres -h localhost——insert mydb>mydb.sql 选项2:在cmd中进行无密码备份 2. pg_dump -U postgres -h localhost——插入mydb>mydb.sql Option3:以gzip格式备份(如果数据库很大) 3.pg_dump -U postgres -h localhost mydb——insert | gzip > mydb.gz
恢复: 1. psql -h localhost -d mydb -U postgres -p 5432 < mydb.sql
我没有看到这里提到转储文件扩展名(*.dump)。
这个解决方案对我很有效:
我有一个转储文件,需要恢复它。
首先,我尝试用pg_restore这样做,并得到:
pg_restore: error: input file appears to be a text format dump. Please use psql.
我用psql做了,工作得很好:
psql -U myUser -d myDataBase < path_to_the_file/file.dump