Created
July 4, 2014 20:56
-
-
Save chintanop/d0c189c2eebd34ce6b68 to your computer and use it in GitHub Desktop.
Copy tables across databases in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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