在Postgres中将表从一个数据库复制到另一个数据库

我试图从一个数据库复制到Postgres的另一个整个表。 有什么build议么?

提取表并将其直接传送到目标数据库:

pg_dump -t table_to_copy source_db | psql target_db 

您也可以使用pgAdmin II中的备份function。 只需按照以下步骤操作

  • 在pgAdmin中,右键点击要移动的表格,select“备份”
  • select输出文件的目录,并将格式设置为“普通”
  • 点击“Dump Options#1”选项卡,选中“Only data”或“Schema”(取决于你在做什么)
  • 在查询部分下,单击“使用列插入”和“用户插入命令”。
  • 点击“备份”button。 这输出到一个.backup文件
  • 用记事本打开这个新文件。 您将看到表/数据所需的插入脚本。 将它们复制并粘贴到pgAdmin的新数据库sql页面中。 作为pgScript运行 – 查询 – >执行为pgScript F6

运作良好,可以一次做多个表格。

使用dblink会更方便!

 truncate table tableA; insert into tableA select * from dblink('dbname=postgres hostaddr=xxx.xxx.xxx.xxx dbname=mydb user=postgres', 'select a,b from tableA') as t1(a text,b text); 

首先安装dblink

你会做这样的事情:

  INSERT INTO t2 select * from dblink('host=1.2.3.4 user=***** password=****** dbname=D1', 'select * t1') tt( id int, col_1 character varying, col_2 character varying, col_3 int, col_4 varchar ); 

在Linux主机上使用psql,可以连接到两台服务器

 ( PGPASSWORD=password1 psql -U user1 -h host1 database1 \ -c "copy (select field1,field2 from table1) to stdout with csv" ) \ | ( PGPASSWORD=password2 psql -U user2 -h host2 database2 \ -c "copy table2 (field1, field2) from stdin csv" ) 

使用pg_dump转储表数据,然后用psql恢复。

如果你有两个远程服务器,那么你可以按照这个:

 pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase 

如果你已经有了schema,它会把源数据库的表格复制到目标数据库的同名表中。

要在本地安装中将表从数据库A移动到数据库B,请使用以下命令:

pg_dump -h localhost -U所有者名称-p 5432 -C -t表名database1 | psql -U所有者名称-h本地主机-p 5432 database2

这是为我工作。 首先转储到一个文件:

 pg_dump -h localhost -U myuser -C -t my_table -d first_db>/tmp/table_dump 

然后加载转储的文件:

 psql -U myuser -d second_db</tmp/table_dump 

与用户5542464和Piyush S. Wanare的答案相同,但分为两步:

 pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase > dump cat dump | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase 

否则pipe道同时询问两个密码。

您必须使用DbLink将一个表数据复制到不同数据库的另一个表中。 您必须安装并configurationDbLink扩展才能执行跨数据库查询。

我已经在这个主题上创build了详细的post。 请访问此链接

我尝试了一些解决scheme,他们真的很有帮助。 根据我的经验,最好的解决scheme是使用psql命令行,但是有时我不喜欢使用psql命令行。 所以这里是pgAdminIII的另一个解决scheme

 create table table1 as( select t1.* from dblink( 'dbname=dbSource user=user1 password=passwordUser1', 'select * from table1' ) as t1( fieldName1 as bigserial, fieldName2 as text, fieldName3 as double precision ) ) 

这种方法的问题是必须写入要复制的表的字段名称及其types。

pgdump总是不工作…

鉴于你在这两个数据库中有相同的表ddl你可以从标准输出和标准input如下所示:

  # grab the list of cols straight from bash psql -d "$src_db"-t -c \ "SELECT column_name FROM information_schema.columns WHERE 1=1 AND table_name='"$table_to_copy"'" # ^^^ filter autogenerated cols if needed psql -d "$src_db" -c \ "copy ( SELECT col_1 , col2 FROM table_to_copy) TO STDOUT" |\ psql -d "$tgt_db" -c "\copy table_to_copy (col_1 , col2) FROM STDIN"