Có nhiều tùy chọn để tăng tốc độ chèn dữ liệu hàng loạt.
1.) commit() sau khi vòng lặp kết thúc:
for ele in coordinates:
cursor.execute('INSERT INTO gmaps (source_latitude, source_longitude, destination_latitude, destination_longitude) VALUES (%s, %s, %s, %s)', (ele[0], ele[1], ele[2], ele[3])))
conn.commit()
2.) Sử dụng trình trợ giúp thực thi nhanh
của psycopg2 , như execute_batch() or execute_values() .
3.) Tập trung chuỗi bằng cách sử dụng mogrify() :
dataText = ','.join(cur.mogrify('(%s,%s,%s,%s)', row) for ele in coordinates)
cur.execute('INSERT INTO gmaps VALUES ' + dataText)
cur.commit()
Để so sánh chi tiết về INSERT tốc độ thực thi hãy xem điều này
điểm chuẩn.