Copy a table from one database to another in Postgres

前端 未结 19 1170
慢半拍i
慢半拍i 2020-11-28 00:21

I am trying to copy an entire table from one database to another in Postgres. Any suggestions?

相关标签:
19条回答
  • 2020-11-28 00:48

    Check this python script

    python db_copy_table.py "host=192.168.1.1 port=5432 user=admin password=admin dbname=mydb" "host=localhost port=5432 user=admin password=admin dbname=mydb" alarmrules -w "WHERE id=19" -v
    Source number of rows = 2
    INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister1',true,false);
    INSERT INTO alarmrules (id,login,notifybyemail,notifybysms) VALUES (19,'mister2',true,false);
    
    0 讨论(0)
  • 2020-11-28 00:49

    First install dblink

    Then, you would do something like:

    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 
    );
    
    0 讨论(0)
  • 2020-11-28 00:49

    Here is what worked for me. First dump to a file:

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

    then load the dumped file:

    psql -U myuser -d second_db</tmp/table_dump
    
    0 讨论(0)
  • 2020-11-28 00:50

    Extract the table and pipe it directly to the target database:

    pg_dump -t table_to_copy source_db | psql target_db
    

    Note: If the other database already has the table set up, you should use the -a flag to import data only, else you may see weird errors like "Out of memory":

    pg_dump -a -t my_table my_db | psql target_db
    
    0 讨论(0)
  • 2020-11-28 00:50

    pg_dump does not work always.

    Given that you have the same table ddl in the both dbs you could hack it from stdout and stdin as follows:

     # 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"
    
    0 讨论(0)
  • 2020-11-28 00:55

    To move a table from database A to database B at your local setup, use the following command:

    pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2
    
    0 讨论(0)
提交回复
热议问题