我正在尝试将数据从一个数据库 (db1) 移动到另一个数据库 (db2)。
经过几次尝试,我想出了下面的代码,但是太慢了。据我估计,数据传输需要+7k小时。
有什么办法可以让它更快吗?我们可以一次处理游标中的多于 1 行吗?
batch_size=10
transfer_table_name='my_table'
with db1.cursor(name=’my_cursor') as cursor:
cursor.itersize=batch_size
cursor.execute(‘select * from schema.table’)
for row in cursor:
csv_io = io.StringIO()
writer=csv.writer(csv_io)
writer.writerow(row)
csv_io.seek(0)
db2.cursor().copy_expert(
'COPY '+
transfer_table_name+
""" FROM STDIN WITH (NULL '', DELIMITER ',', FORMAT CSV)""",
csv_io
)
db2.commit()
如果以更大的块传输行,速度会快得多
batch_size = 1000
transfer_table_name = 'my_table'
with db1.cursor(name='my_cursor') as cursor:
cursor.itersize = batch_size
cursor.execute('SELECT * FROM schema.table')
while True:
rows = cursor.fetchmany(batch_size)
if not rows:
break
csv_io = io.StringIO()
writer = csv.writer(csv_io)
writer.writerows(rows)
csv_io.seek(0)
with db2.cursor() as db2_cursor:
db2_cursor.copy_expert(
f'COPY {transfer_table_name} FROM STDIN WITH (NULL \'\', DELIMITER \',\', FORMAT CSV)',
csv_io
)
db2.commit()