Skip to content

Instantly share code, notes, and snippets.

@chintanop
Created July 4, 2014 20:56
Show Gist options
  • Save chintanop/d0c189c2eebd34ce6b68 to your computer and use it in GitHub Desktop.
Save chintanop/d0c189c2eebd34ce6b68 to your computer and use it in GitHub Desktop.
Copy tables across databases in Python
def copy_table(self, table_name, source_conn, target_conn):
""" copies all records from table_name from source to target db """
scursor = source_conn.cursor()
tcursor = target_conn.cursor()
scursor.execute("SELECT * from "+table_name)
desc = scursor.description
columns = ",".join([col[0] for col in desc])
values_q = ",".join(["%(key"+str(indx)+")s" for indx, col in enumerate(desc)])
for row in scursor.fetchall():
insrt_sql = (
"INSERT into "+table_name+"( "+columns+" ) "
"values ("+values_q+")"
)
qdict = {}
for indx, row_val in enumerate(row):
qdict["key"+str(indx)] = row_val
tcursor.execute(insrt_sql, qdict)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment