Python Postgres Best way to insert data from table on one DB to another table on another DB

折月煮酒 提交于 2020-01-17 05:50:10

问题


I have the following python code that copies content of a table on postgres DB1 and INSERTS into a similar table on postgres DB2.

I want to speed it up by using BULK INSERTS. How do I achieve this

import psycopg2
import sys
import os


all_data = []


try:
    connec = psycopg2.connect("host = server1 dbname = DB1 ")
    connecc = psycopg2.connect("host = server2 dbname = DB2 ")
    connec.autocommit = True
    connecc.autocommit = True
except:
    print("I am unable to connect to the database.")


cur = connec.cursor()

curr = connecc.cursor()



cur.execute("""SELECT * FROM TABLE1""")


curr.execute("TRUNCATE table TABLE2")

rows = cur.fetchall()

for row in rows:
    all_data = row


    curr.execute("INSERT INTO TABLE2 "
                 "VALUES(%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,     %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s,"
             " %s)"
    ,(all_data[0],  all_data[1],all_data[2],all_data[3],all_data[4],     all_data[5], all_data[6], all_data[7],
      all_data[8], all_data[9], all_data[10], all_data[11],     all_data[12], all_data[13], all_data[14],all_data[15],
      all_data[16], all_data[17], all_data[18], all_data[19],
      all_data[20], all_data[21], all_data[22]))

    connecc.commit()

connec.close()

connecc.close()

回答1:


Simpliest way is to use FDW (foreign data wrappers) for connect both servers (https://www.postgresql.org/docs/9.5/static/postgres-fdw.html). And operate by both table in one server.

Second way is use dblink (https://www.postgresql.org/docs/9.6/static/dblink.html).

By both this way data directly pass from one server to second (no via your program)



来源:https://stackoverflow.com/questions/41965879/python-postgres-best-way-to-insert-data-from-table-on-one-db-to-another-table-on

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!