使用PostgreSQL在数据库之间传输数据

Nic*_*uri 50 sql postgresql insertion

我需要从另一个数据库传输一些数据.旧数据库名为paw1.movi​​esDB,新数据库名为paw1.每个表的模式如下.

Awards (name of the table)(new DB)
Id [PK] Serial           Award

Nominations (name of the table) (old DB)
Id [PK] Serial           nominations
Run Code Online (Sandbox Code Playgroud)

如何将数据从旧数据库复制到新数据库?

Nat*_*ate 74

我只是必须这样做,所以我想我会在这里发布食谱.这假设两个数据库都在同一台服务器上.

首先,将表从旧数据库复制到新数据库(因为显然您无法在数据库之间移动数据).在命令行:

pg_dump -U postgres -t <old_table> <old_database> | psql -U postgres -d <new_database>

# Just adding extra space here so scrollbar doesn't hide the command
Run Code Online (Sandbox Code Playgroud)

接下来,将复制的表的权限授予新数据库的用户.登录psql:

psql -U postgres -d <new_database>

ALTER TABLE <old_table> OWNER TO <new_user>;

\q
Run Code Online (Sandbox Code Playgroud)

最后,将数据从旧表复制到新表.以新用户身份登录,然后:

INSERT INTO <new_table> (field1, field2, field3) 
SELECT field1, field2, field3 from <old_table>;
Run Code Online (Sandbox Code Playgroud)

完成!

  • 如何为远程服务器做到这一点? (7认同)
  • @DevR,只需添加-h <远程主机名> (3认同)

leo*_*loy 33

数据库在PostgreSQL中被隔离; 当您连接到只连接到一个数据库的PostgreSQL服务器时,您无法使用SQL查询将数据从一个数据库复制到另一个数据库.

如果你来自MySQL:MySQL调用(松散地)" 数据库 "是PostgreSQL 中的" 模式 " - 一种命名空间.PostgreSQL数据库可以有许多模式,每个模式都有其表和视图,您可以使用schema.table语法从一个模式复制到另一个模式.

如果你真的有两个不同的PostgreSQL数据库,那么将数据从一个数据库传输到另一个数据库的常用方法是将表(with pg_dump -t)导出到一个文件,然后将它们导入另一个数据库(with psql).

如果你真的需要从不同的PostgreSQL数据库获取数据,那么另一个选项 - 在Grant Johnson的答案中提到 - 是dblink,这是一个额外的模块(in contrib/).


cri*_*aig 21

这对我有用,可以从我的localhost远程复制一个表到Heroku的postgresql:

pg_dump -C -t source_table -h localhost source_db | psql -h destination_host -U destination_user -p destination_port destination_db

这会为您创建表格.

对于另一个方向(从Heroku到本地) pg_dump -C -t source_table -h source_host -U source_user -p source_port source_db | psql -h localhost destination_db


Thi*_*edo 11

来自:hxxp://dbaspot.c om/postgresql/348627-pg_dump -t-give-where-condition.html(注意:链接现已断开)

# create temp table with the data
psql mydb
CREATE TABLE temp1 (LIKE mytable);
INSERT INTO temp1 SELECT * FROM mytable WHERE myconditions;
\q

# export the data to a sql file
pg_dump --data-only --column-inserts -t temp1 mtdb > out.sql
psql mydb
DROP TABLE temp1;
\q

# import temp1 rows in another database
cat out.sql | psql -d [other_db]
psql other_db
INSERT INTO mytable (SELECT * FROM temp1);
DROP TABLE temp1;
Run Code Online (Sandbox Code Playgroud)

另一种在遥控器中有用的方法

  # export a table csv and import in another database
  psql-remote> COPY elements TO '/tmp/elements.csv' DELIMITER ',' CSV HEADER;
  $ scp host.com:/tmp/elements.csv /tmp/elements.csv
  psql-local> COPY elements FROM '/tmp/elements.csv' DELIMITER ',' CSV;
Run Code Online (Sandbox Code Playgroud)


Gra*_*son 8

复制它有三种选择,如果这是一次性的:

  1. 使用db_link(我认为它仍然在contrib中)
  2. 让应用程序完成工作.
  3. 进出口

如果这是一个持续的需求,答案是:

  1. 更改为同一DB中的模式
  2. db_link