我想复制一个生产PostgreSQL数据库到一个开发服务器。最快最简单的方法是什么?
当前回答
以数据库名称运行此命令,如果要备份,则转储数据库。
pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}
eg. pg_dump -U postgres mydbname -f mydbnamedump.sql
现在将这个转储文件scp到您想要复制DB的远程机器。
eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/
在远程机器上,在~/some/文件夹中运行以下命令来恢复DB。
psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}
eg. psql -U postgres -d mynewdb -f mydbnamedump.sql
其他回答
我努力了很多,最终让我在Rails 4中工作的方法是:
在旧服务器上
sudo su - postgres
pg_dump -c --inserts old_db_name > dump.sql
我必须使用postgres linux用户来创建转储。我还必须使用-c来强制在新服务器上创建数据库。——inserts告诉它使用INSERT()语法,否则对我来说是无效的:(
然后,在新服务器上,simpy:
sudo su - postgres
psql new_database_name < dump.sql
传输转储。我简单地使用“cat”来打印内容,而不是“nano”来重新创建它复制粘贴内容。
此外,我在两个数据库上使用的角色是不同的,所以我必须在转储中找到-替换所有的所有者名称。
您不需要创建中间文件。你可以这样做
pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname
or
pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname
使用PSQL或pg_dump连接到远程主机。
对于大数据库或慢速连接,转储文件和传输压缩文件可能更快。
正如Kornel所说,没有必要转储到中间文件,如果你想压缩工作,你可以使用压缩隧道
pg_dump -C dbname | bzip2 | ssh remoteuser@remotehost "bunzip2 | psql dbname"
or
pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"
但是这个解决方案还需要在两端都获得一个会话。
注:pg_dump用于备份,psql用于恢复。因此,这个答案中的第一个命令是从本地复制到远程,第二个命令是从远程复制到本地。更多-> https://www.postgresql.org/docs/9.6/app-pgdump.html
转储数据库:pg_dump database_name_name > backup.sql
导入数据库:psql db_name < backup.sql
以数据库名称运行此命令,如果要备份,则转储数据库。
pg_dump -U {user-name} {source_db} -f {dumpfilename.sql}
eg. pg_dump -U postgres mydbname -f mydbnamedump.sql
现在将这个转储文件scp到您想要复制DB的远程机器。
eg. scp mydbnamedump.sql user01@remotemachineip:~/some/folder/
在远程机器上,在~/some/文件夹中运行以下命令来恢复DB。
psql -U {user-name} -d {desintation_db}-f {dumpfilename.sql}
eg. psql -U postgres -d mynewdb -f mydbnamedump.sql
接受的答案是正确的,但如果你想避免交互式输入密码,你可以使用这个:
PGPASSWORD={{export_db_password}} pg_dump --create -h {{export_db_host}} -U {{export_db_user}} {{export_db_name}} | PGPASSWORD={{import_db_password}} psql -h {{import_db_host}} -U {{import_db_user}} {{import_db_name}}
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 截断Postgres数据库中的所有表
- 什么是分片,为什么它很重要?
- 如何连接列在Postgres选择?
- 数据库触发器是必要的吗?
- 为什么我应该使用基于文档的数据库而不是关系数据库?
- 哪个更快/最好?SELECT *或SELECT columnn1, colum2, column3等
- 将varchar字段的类型更改为整数:"不能自动转换为整数类型"
- 将值从同一表中的一列复制到另一列
- PostgreSQL可以索引数组列吗?
- 什么是数据库池?
- 关于数据库,每个开发人员应该知道些什么?
- PostgreSQL:角色不允许登录
- "where 1=1"语句
- 如何查找Postgres / PostgreSQL表及其索引的磁盘大小