2016-07-07 22 views
1

工作我試圖從一個數據庫(PostgreSQL系統)傳輸大量數據(15二)其他與Python/psycopg2的碼頭工人。我的碼頭有4 GB的內存,並且內存不足。Python的psycopg2 - 大數據

我做錯了什麼?

cursor = conn.cursor() 
cursor.execute('select * from schema.table') 
for row in cursor: 
    tp = tuple(map(lambda x: x.encode('utf-8'), row) 
    cursor.execute('Insert into table2 values {}'.format(tp)) 
    conn.commit() 
+0

到這裏看看:http://stackoverflow.com/a/10147451/771848。希望有所幫助。 – alecxe

+0

謝謝。但是我的問題是使用光標,即將所有數據存入內存。 –

回答

0

使用copy_to and copy_from

f = open('t.txt', 'wb') 
conn = psycopg2.connect(database='source_db') 
cursor = conn.cursor() 
cursor.copy_to(f, 'source_table') 
conn.close() 
f.close() 

f = open('t.txt', 'r') 
conn = psycopg2.connect(database='target_db') 
cursor = conn.cursor() 
cursor.copy_from(f, 'target_table') 
conn.close() 
f.close() 
+0

這解決了這個問題。謝謝。數據流,我必須做什麼? –