I have a code as follows:
import pg
import MySQLdb
db_postgre = pg.connect(dbname=...,user=...,passwd=...,host=.., port=...)
db_mysql=MySQLdb.Connect(user=...,passwd=...,db=..., host=...)
cur = db_mysql.cursor(MySQLdb.cursors.DictCursor)
cur.execute ("""SELECT X,Y,Z FROM tab_a""")
data = crs.fetchall ()
for row in data :
#INSERT THE ROW (X,Y,Z) TO POSTGRESQL TABLE.
The table in PostgreSQL (post_tab_a) is identical to the one in MySQL .
meaning it also has X,Y,Z
all types are TEXT.
Is it possible to perform insert directly from cur? What is the easiyest way to do this insert?
asked Apr 10, 2016 at 11:47
java
1,2345 gold badges17 silver badges36 bronze badges
1 Answer 1
Simply open another cursor for Postgre for the iterative inserts. There wouldn't be any named confusion as tables correspond to their cursor/connection objects:
import pg
import MySQLdb
# DB CONNECTIONS
db_postgre = pg.connect(dbname=...,user=...,passwd=...,host=.., port=...)
db_mysql = MySQLdb.Connect(user=...,passwd=...,db=..., host=...)
# CURSORS
mycur = db_mysql.cursor()
postcur = db_postgre.cursor()
mycur.execute("SELECT X,Y,Z FROM tab_a")
for row in mycur.fetchall():
postcur.execute("INSERT INTO tab_a (X,Y,Z) VALUES (%s, %s, %s)", \
(row['X'], row['Y'], row['Z']))
db_postgre.commit()
# CLOSE CURSORS
postcur.close()
mycur.close()
# CLOSE CONNECTIONS
db_postgre.close()
db_mysql.close()
answered Apr 10, 2016 at 15:03
Parfait
108k19 gold badges103 silver badges138 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
default
insert into post_tab_a (x,y,z) select x,y,z from tab_a. The issue is that post_tab_a is in postgresql and tab_a is in MYSql