我试图在Postgres中从一个数据库复制整个表到另一个数据库。有什么建议吗?


当前回答

如果你在Windows上运行pgAdmin(备份:pg_dump,恢复:pg_restore),默认情况下,它会尝试将文件输出到c:\Windows\System32,这就是为什么你会得到拒绝权限/访问的错误,而不是因为用户postgres不够高。以管理员身份运行pgAdmin,或者直接选择Windows系统文件夹以外的输出位置。

其他回答

与user5542464和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

否则,管道将同时询问两个密码。

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

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 
  )
 )

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

你可以通过两个简单的步骤做到:

# dump the database in custom-format archive
pg_dump -Fc mydb > db.dump

# restore the database
pg_restore -d newdb db.dump

如果是远程数据库:

# dump the database in custom-format archive
pg_dump -U mydb_user -h mydb_host -t table_name -Fc mydb > db.dump

# restore the database
pg_restore -U newdb_user -h newdb_host -d newdb db.dump

以下是对我有效的方法。 第一次转储到一个文件:

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

我使用的是DataGrip (By Intellij Idea)。将数据从一个表(在不同的数据库中)复制到另一个表非常容易。

首先,确保你在Data Grip中连接了两个数据源。

选择源表并按F5或(右键单击->选择复制表到。)

这将显示所有表的列表(您也可以在弹出窗口中使用表名进行搜索)。选择你的目标,然后按OK。

DataGrip将为您处理其他一切。