Created
May 10, 2016 17:35
-
-
Save gwax/589befb7343ef423aa3f4ea03ceaafdb to your computer and use it in GitHub Desktop.
Sqlalchemy result batching for inserts
This file contains 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 batch_results(results, batch_size=10000): | |
batch = results.fetchmany(batch_size) | |
while batch: | |
yield batch | |
batch = results.fetchmany(batch_size) | |
for batch in batch_results(conn.execute(query)): | |
new_rows = [dict(row) for row in batch] | |
# Modify new_rows here, if needed | |
conn.execute(table.insert(), new_rows) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I came up with this solution that is shorter and delegates more work to Python. This uses of the two-argument, sentinel usage of iter and the fact that fetchmany returns an empty list when all rows have been exhausted: