简体   繁体   English

使用命令行恢复 postgres 备份文件?

[英]Restore a postgres backup file using the command line?

Locally, I use pgadmin3.在本地,我使用 pgadmin3。 On the remote server, however, I have no such luxury.然而,在远程服务器上,我没有这样的奢侈。

I've already created the backup of the database and copied it over, but is there a way to restore a backup from the command line?我已经创建了数据库的备份并将其复制过来,但是有没有办法从命令行恢复备份? I only see things related to GUI or to pg_dumps.我只看到与 GUI 或 pg_dumps 相关的内容。

There are two tools to look at, depending on how you created the dump file.有两种工具可供查看,具体取决于您创建转储文件的方式。

Your first source of reference should be the man page pg_dump as that is what creates the dump itself.您的第一个参考来源应该是手册页pg_dump ,因为它是创建转储本身的原因。 It says:它说:

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.脚本转储是纯文本文件,其中包含将数据库重建到保存时的状态所需的 SQL 命令。 To restore from such a script, feed it to psql(1).要从这样的脚本中恢复,请将其提供给 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.甚至在其他 SQL 数据库产品上也进行了一些修改。

The alternative archive file formats must be used with pg_restore(1) to rebuild the database.替代归档文件格式必须与 pg_restore(1) 一起使用来重建数据库。 They allow pg_restore to be selective about what is restored, or even to reorder the items prior to being restored.它们允许 pg_restore 选择要恢复的内容,甚至可以在恢复之前重新排序项目。 The archive file formats are designed to be portable across architectures.存档文件格式旨在跨架构移植。

So depends on the way it was dumped out.所以取决于它被丢弃的方式。 If using Linux/Unix, you can probably figure it out using the excellent file(1) command - if it mentions ASCII text and/or SQL, it should be restored with psql otherwise you should probably use pg_restore .如果使用 Linux/Unix,您可能可以使用出色的file(1)命令来解决 - 如果它提到 ASCII 文本和/或 SQL,则应该使用psql恢复它,否则您可能应该使用pg_restore

Restoring is pretty easy:恢复非常简单:

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

Check out their respective manpages - there's quite a few options that affect how the restore works.查看他们各自的联机帮助页 - 有很多选项会影响恢复的工作方式。 You may have to clean out your "live" databases or recreate them from template0 (as pointed out in a comment) before restoring, depending on how the dumps were generated.您可能必须在恢复之前清除“实时”数据库或从 template0 重新创建它们(如评论中指出的那样),具体取决于转储的生成方式。

create backup创建备份

pg_dump -h localhost -p 5432 -U postgres -F c -b -v -f 
"/usr/local/backup/10.70.0.61.backup" old_db

-F c is custom format (compressed, and able to do in parallel with -j N ) -b is including blobs , -v is verbose , -f is the backup file name . -F c自定义格式(压缩,并且能够与-j N并行执行) -b包括 blobs-v详细的, -f备份文件名

restore from backup从备份恢复

pg_restore -h localhost -p 5432 -U postgres -d old_db -v 
"/usr/local/backup/10.70.0.61.backup"

important to set -h localhost - option重要设置-h localhost - 选项

You might need to be logged in as postgres in order to have full privileges on databases.您可能需要以postgres身份登录才能拥有数据库的完全权限。

su - postgres
psql -l                      # will list all databases on Postgres cluster

pg_dump/pg_restore pg_dump/pg_restore

  pg_dump -U username -f backup.dump database_name -Fc 

switch -F specify format of backup file:开关-F指定备份文件的格式:

  • c will use custom PostgreSQL format which is compressed and results in smallest backup file size c将使用自定义的 PostgreSQL 格式,该格式被压缩并导致最小的备份文件大小
  • d for directory where each file is one table d表示每个文件是一个表的目录
  • t for TAR archive (bigger than custom format) t用于 TAR 存档(大于自定义格式)
  • -h / --host Specifies the host name of the machine on which the server is running -h / --host指定运行服务器的机器的主机名
  • -W / --password Force pg_dump to prompt for a password before connecting to a database -W / --password强制pg_dump在连接到数据库之前提示输入密码

restore backup:恢复备份:

   pg_restore -d database_name -U username -C backup.dump

Parameter -C should create database before importing data.参数-C应该在导入数据之前创建数据库。 If it doesn't work you can always create database eg.如果它不起作用,您可以随时创建数据库,例如。 with command (as user postgres or other account that has rights to create databases) createdb db_name -O owner使用命令(作为用户postgres或其他有权创建数据库的帐户) createdb db_name -O owner

pg_dump/psql pg_dump/psql

In case that you didn't specify the argument -F default plain text SQL format was used (or with -F p ).如果您没有指定参数-F使用默认纯文本 SQL 格式(或使用-F p )。 Then you can't use pg_restore .然后你不能使用pg_restore You can import data with psql .您可以使用psql导入数据。

backup:备份:

pg_dump -U username -f backup.sql database_name

restore:恢复:

psql -d database_name -f backup.sql

POSTGRESQL 9.1.12 PostgreSQL 9.1.12

DUMP:倾倒:

pg_dump -U user db_name > archive_name.sql

put the user password and press enter.输入用户密码并按回车。

RESTORE:恢复:

psql -U user db_name < /directory/archive.sql

put the user password and press enter.输入用户密码并按回车。

Below is my version of pg_dump which I use to restore the database:下面是我用来恢复数据库的pg_dump版本:

pg_restore -h localhost -p 5432 -U postgres -d my_new_database my_old_database.backup

or use psql :或使用psql

psql -h localhost -U postgres -p 5432 my_new_database < my_old_database.backup

where -h host, -p port, -u login username, -d name of database其中-h主机, -p端口, -u登录用户名, -d数据库名称

Backup and restore with GZIP使用 GZIP 备份和恢复

For larger size database this is very good对于较大的数据库,这非常好

backup备份

pg_dump -U user -d mydb | gzip > mydb.pgsql.gz

restore恢复

gunzip -c mydb.pgsql.gz | psql dbname -U user

https://www.postgresql.org/docs/14/backup-dump.html https://www.postgresql.org/docs/14/backup-dump.html

这对我有用:

pg_restore --verbose --clean --no-acl --no-owner --host=localhost --dbname=db_name --username=username latest.dump
Backup:  $ pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}

Restore: $ psql -U {user-name} -d {desintation_db} -f {dumpfilename.sql}

try this:尝试这个:

psql -U <username> -d <dbname> -f <filename>.sql

Restore DB psql from .sql file从 .sql 文件恢复数据库 psql

1. Open the Terminal. 1. 打开终端。

2. Backup your database with following command 2. 使用以下命令备份您的数据库

your postgres bin -> /opt/PostgreSQL/9.1/bin/你的 postgres bin -> /opt/PostgreSQL/9.1/bin/

your source database server -> 192.168.1.111您的源数据库服务器-> 192.168.1.111

your backup file location and name -> /home/dinesh/db/mydb.backup您的备份文件位置和名称 -> /home/dinesh/db/mydb.backup

your source db name -> mydatabase您的源数据库名称 - > mydatabase

/opt/PostgreSQL/9.1/bin/pg_dump --host '192.168.1.111' --port 5432 --username "postgres" --no-password  --format custom --blobs --file "/home/dinesh/db/mydb.backup" "mydatabase"

3. Restore mydb.backup file into destination. 3. 将 mydb.backup 文件恢复到目的地。

your destination server -> localhost您的目标服务器-> localhost

your destination database name -> mydatabase您的目标数据库名称 -> mydatabase

Create database for restore the backup.创建用于恢复备份的数据库。

/opt/PostgreSQL/9.1/bin/psql -h 'localhost' -p 5432 -U postgres -c "CREATE DATABASE mydatabase"

Restore the backup.恢复备份。

/opt/PostgreSQL/9.1/bin/pg_restore --host 'localhost' --port 5432 --username "postgres" --dbname "mydatabase" --no-password --clean "/home/dinesh/db/mydb.backup"

If you create a backup using pg_dump you can easily restore it in the following way:如果您使用 pg_dump 创建备份,您可以通过以下方式轻松恢复它:

  1. Open command line window打开命令行窗口
  2. Go to Postgres bin folder.转到 Postgres bin 文件夹。 For example: cd "C:\ProgramFiles\PostgreSQL\9.5\bin"例如: cd "C:\ProgramFiles\PostgreSQL\9.5\bin"
  3. Enter the command to restore your database.输入命令以恢复您的数据库。 For example: psql.exe -U postgres -d YourDatabase -f D:\Backup\.sql
  4. Type password for your postgres user输入您的 postgres 用户的密码
  5. Check the restore process检查恢复过程

I didnt see here mentions about dump file extension (*.dump).我没有看到这里提到转储文件扩展名 (*.dump)。

This solution worked for me:这个解决方案对我有用:

I got a dump file and needed to recover it.我有一个转储文件,需要恢复它。

First I tried to do this with pg_restore and got:首先,我尝试使用pg_restore执行此操作并得到:

pg_restore: error: input file appears to be a text format dump. Please use psql.

I did it with psql and worked well:我用psql做到了,效果很好:

psql -U myUser -d myDataBase < path_to_the_file/file.dump

1) Open psql terminal. 1) 打开 psql 终端。

2) Unzip/ untar the dump file. 2) 解压/解压转储文件。

3) Create an empty database. 3) 创建一个空数据库。

4) use the following command to restore the .dump file 4)使用以下命令恢复.dump文件

<database_name>-# \i <path_to_.dump_file>

Backup & Restore备份和恢复

This is the combo I'm using to backup , drop, create and restore my database (on macOS and Linux):这是我用来备份、删除、创建和恢复我的数据库的组合(在 macOS 和 Linux 上):

sudo -u postgres pg_dump -Fc mydb > ./mydb.sql
sudo -u postgres dropdb mydb
sudo -u postgres createdb -O db_user mydb
sudo -u postgres pg_restore -d mydb < ./mydb.sql

Misc杂项

  • -Fc will compress the database ( f ormat c ustom ) -Fc将压缩数据库(格式自定义
  • List PostgreSQL users: sudo -u postgres psql -c "\du+"列出 PostgreSQL 用户: sudo -u postgres psql -c "\du+"
  • You may want to add hostname and date to ./mydb.sql , then change it by:您可能希望将主机名日期添加到./mydb.sql ,然后通过以下方式进行更改:
     ./`hostname`_mydb_`date +"%Y%m%d_%H%M"`.sql

To restore a dump file恢复转储文件

psql -d [Dbname] -U [UserName] -p 5432 < [FileLocation]

To restore a .SQL file恢复 .SQL 文件

pg_restore -U [Username] -d [Dbname] -1 [FileLocation]

If you get user authentication errors, go to the file pg_hba.conf which is in PSQL/data folder in your program files, and change the "METHOD" to "Trust".如果您遇到用户验证错误,请转到程序文件中 PSQL/data 文件夹中的文件 pg_hba.conf,并将“METHOD”更改为“Trust”。 Restart you psql serive in windows services(Win + R --> services.msc).在 Windows 服务中重新启动 psql 服务(Win + R --> services.msc)。

尝试:

pg_restore -h localhost -p 5432 -U <username> -d <dbname> -1 <filename>

Restoring a postgres backup file depends on how did you take the backup in the first place.恢复 postgres 备份文件取决于您最初是如何进行备份的。

If you used pg_dump with -F c or -F d you need to use pg_restore otherwise you can just use如果您将 pg_dump 与 -F c 或 -F d 一起使用,则需要使用 pg_restore 否则您可以使用

psql -h localhost -p 5432 -U postgres < backupfile psql -h localhost -p 5432 -U postgres <备份文件

9 ways to backup and restore postgres databases 备份和恢复 postgres 数据库的 9 种方法

As below link said, you can use psql command for restoring the dump file:如下链接所述,您可以使用 psql 命令恢复转储文件:

https://www.postgresql.org/docs/8.1/static/backup.html#BACKUP-DUMP-RESTORE https://www.postgresql.org/docs/8.1/static/backup.html#BACKUP-DUMP-RESTORE

psql dbname < infile

if you need to set username just add the username after the command like:如果您需要设置用户名,只需在命令后添加用户名,例如:

psql dbname < infile username

Try to see if the following commands can help you:尝试查看以下命令是否可以帮助您:

sudo su - yourdbuser
psql
\i yourbackupfile

Sorry for the necropost, but these solutions did not work for me.对不起,necropost,但这些解决方案对我不起作用。 I'm on postgres 10. On Linux:我在 postgres 10 上。在 Linux 上:

  1. I had to change directory to my pg_hba.conf.我不得不将目录更改为我的 pg_hba.conf。
  2. I had to edit the file to change method from peer to md5 as stated here我必须编辑文件以将方法从对等更改为 md5,如此所述
  3. Restart the service: service postgresql-10 restart重启服务: service postgresql-10 restart
  4. Change directory to where my backup.sql was located and execute:将目录更改为我的 backup.sql 所在的位置并执行:
    psql postgres -d database_name -1 -f backup.sql

    -database_name is the name of my database -database_name 是我的数据库的名称

    -backup.sql is the name of my .sql backup file. -backup.sql 是我的 .sql 备份文件的名称。

The shortest way with no password prompt无密码提示的最短路径

psql "postgresql://<db_user>:<db_pass>@<ip>:<port>/<db_name>" < "backup.sql"

If you are using Windows OS如果您使用的是 Windows 操作系统

psql.exe "postgresql://<db_user>:<db_pass>@<ip>:<port>/<db_name>" < "backup.sql"

I was having authentication problems running pg_dump, so I moved my dump file我在运行 pg_dump 时遇到了身份验证问题,所以我移动了我的转储文件

mv database_dump /tmp

into the temp directory and then ran进入临时目录,然后运行

su -u postgres
cd /tmp
pg_restore database_dump

If you have a large database dump, you may just want to create another directory where your current user and the postgres user can access and putting the database dump file into that.如果您有一个大型数据库转储,您可能只想创建另一个目录,您的当前用户和 postgres 用户可以访问该目录并将数据库转储文件放入其中。

If you have a backup SQL file then you can easily Restore it.如果您有备份 SQL 文件,那么您可以轻松地恢复它。 Just follow the instructions, given in the below只需按照以下说明进行操作

1. At first, create a database using pgAdmin or whatever you want (for example my_db is our created db name)
2. Now Open command line window
3. Go to Postgres bin folder. For example:  cd "C:\ProgramFiles\PostgreSQL\pg10\bin"
4. Enter the following command to restore your database: psql.exe -U postgres -d my_db -f D:\Backup\backup_file_name.sql 

Type password for your postgres user if needed and let Postgres to do its work.如果需要,输入您的 postgres 用户的密码并让 Postgres 完成其工作。 Then you can check the restore process.然后您可以检查还原过程。

Backup==>备份==>

Option1: To take backup along with password in cmd选项1:在cmd中与密码一起备份
1.PGPASSWORD="mypassword" pg_dump -U postgres -h localhost --inserts mydb>mydb.sql
Option2: To take backup without password in cmd选项2:在cmd中进行无密码备份
2. pg_dump -U postgres -h localhost --inserts mydb>mydb.sql
Option3: To take backup as gzip(if database is huge)选项3:以 gzip 格式备份(如果数据库很大)
3. pg_dump -U postgres -h localhost mydb --inserts | gzip > mydb.gz

Restore:恢复:
1. psql -h localhost -d mydb -U postgres -p 5432 < mydb.sql

This solution only works for Windows .此解决方案仅适用于Windows

First, ensure you have already added the postgres bin folder to the "Path" environment variable (in my case this folder is C:\Program Files\PostgreSQL\12\bin).首先,确保您已经将 postgres bin 文件夹添加到“路径”环境变量中(在我的例子中,这个文件夹是 C:\Program Files\PostgreSQL\12\bin)。

Then, open the Windows command interpreter (cmd), go to the folder where you have the .sql file and execute this command:然后,打开 Windows 命令解释器 (cmd),转到您拥有 .sql 文件的文件夹并执行以下命令:

pg_restore -U userName -d database-1 backupfile.sql pg_restore -U 用户名 -d database-1 backupfile.sql

For example:例如:

pg_restore -U sam -d SamDataBase -1 SamDataBaseBackup.sql pg_restore -U sam -d SamDataBase -1 SamDataBaseBackup.sql

(It can ask you for the password of the user so ensure to type it correctly and then click enter) (它可以要求您输入用户的密码,因此请确保输入正确,然后单击输入)

Pura vida!普拉维达!

If you have created a new database named mydb , To restore a .sql dump to that database with psql,如果您创建了一个名为mydb的新数据库,要使用 psql 将 .sql 转储恢复到该数据库,

psql --file=dump.sql --username=postgres --host=localhost --port=5432 mydb

the password will be prompted by psql psql会提示密码

The connection options are连接选项是

  -h, --host=HOSTNAME      database server host or socket directory (default: "/var/run/postgresql")
  -p, --port=PORT          database server port (default: "5432")
  -U, --username=USERNAME  database user name (default: "xyz")
  -w, --no-password        never prompt for password
  -W, --password           force password prompt (should happen automatically)

If you are using docker, this answer may be helpful.如果您使用的是 docker,此答案可能会有所帮助。

  1. Start the container启动容器
    docker start <postgres_container_id>
  2. Access bash inside container在容器内访问 bash
     docker exec -it <postgres_container_id> bash
  3. Copy the .tar backup file to docker container (In another window).tar备份文件复制到 docker 容器(在另一个窗口中)
     docker cp postgres_dump.tar <postgres_container_id>:/
  4. Restore the backup恢复备份
    pg_restore -c -U <postgres-user> -d <password> -v "postgres_dump.tar" -W
  5. Enter password输入密码

If you want to backup your data or restore data from a backup, you can run the following commands:如果要备份数据或从备份中恢复数据,可以运行以下命令:

  1. To create backup of your data, go to your postgres \bin\ directory like C:\programfiles\postgres\10\bin\ and then type the following command:要创建数据备份,请转到您的 postgres \bin\ 目录,例如C:\programfiles\postgres\10\bin\ ,然后键入以下命令:

     pg_dump -FC -U ngb -d ngb -p 5432 >C:\BACK_UP\ngb.090718_after_readUpload.backup
  2. To restore data from a backup, go to your postgres \bin\ directory like C:\programfiles\postgres\10\bin\ and then type below command:要从备份中恢复数据,请转到您的 postgres \bin\ 目录,例如C:\programfiles\postgres\10\bin\ ,然后键入以下命令:

     C:\programFiles\postgres\10\bin> pg_restore -Fc -U ngb -d ngb -p 5432 <C:\ngb.130918.backup

    Please make sure that the backup file exists.请确保备份文件存在。

Save and restore the exact same state with compressed dump使用压缩转储保存和恢复完全相同的 state

Other answers gave all the key bits separately, but hopefully this will provide be the "just works save and restore to exact state" command pair.其他答案分别给出了所有关键位,但希望这将提供“保存并恢复到准确状态”命令对。

Dump to file mydb.psql :转储到文件mydb.psql

PGPASSWORD=mypassword pg_dump -U my_username -h localhost mydb -Fc -f mydb.psql

Restore:恢复:

PGPASSWORD=mypassword pg_restore -U my_username -h localhost \
  --clean -d mydb -v mydb.psql

Some of the flags:一些标志:

  • -Fc : Format Compressed, as opposed to plaintext. -Fc :格式压缩,而不是纯文本。

    file tmp.psql says: file tmp.psql说:

     tmp.psql: PostgreSQL custom database dump - v1.14-0
  • --clean : destroy the target DB before restoring it, thus returning to the exact same pristine state. --clean :在恢复之前销毁目标数据库,从而返回到完全相同的原始 state。

    Any data created after the dump will be lost.转储后创建的任何数据都将丢失。

PGPASSWORD , -U and -h can of course be modified depending on your login method, eg without PGPASSWORD you're prompted for a password, and none of those are needed if you set up peer auth locally. PGPASSWORD-U-h当然可以根据您的登录方法进行修改,例如,如果没有PGPASSWORD ,系统会提示您输入密码,如果您在本地设置对等身份验证,则不需要这些。

Tested on Ubuntu 22.04, PostgreSQL 14.5.在 Ubuntu 22.04、PostgreSQL 14.5 上测试。

Follow these 3 steps :请遵循以下 3 个步骤:

  1. start postgres server - sudo systemctl start postgresql启动 postgres 服务器 - sudo systemctl start postgresql
  2. enable same - sudo systemctl enable postgresql启用相同 - sudo systemctl enable postgresql
  3. restore command - pg_restore -h localhost -p 5432 -U postgres -d old_db恢复命令 - pg_restore -h localhost -p 5432 -U postgres -d old_db

assuming that the dump is there in the same directory假设转储在同一目录中

Links :链接

https://www.postgresqltutorial.com/postgresql-restore-database https://askubuntu.com/questions/50621/cannot-connect-to-postgresql-on-port-5432 https://www.postgresqltutorial.com/postgresql-restore-database https://askubuntu.com/questions/50621/cannot-connect-to-postgresql-on-port-5432

See below example its working见下面的例子它的工作

C:/Program Files/PostgreSQL/9.4/bin\pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "newDatabase" --no-password --verbose C:/Program Files/PostgreSQL/9.4/bin\pg_restore.exe --host localhost --port 5432 --username "postgres" --dbname "newDatabase" --no-password --verbose

" C:\Users\Yogesh\Downloads\new Download\DB.backup " " C:\Users\Yogesh\Downloads\new 下载\DB.backup "

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM