Is there a way to bulk insert record into DB with sqlalchemy,
I have a list of tuple and I want to insert them directly into DB with sqlalchemy execute command.
Is there any way to perform the task.
Here is the sample that I want to insert
This is the row_chunk :
[(1001, ‘1bz’, 120), (1002, ‘7zmk’, 150), (1003, ‘8wqt’, 170), (1005, ‘1qpo’, 1100), (1006, ‘5qop’, 4400), (1006, ‘5qop’, 4400), (1007, ’22mn’, 227), (1008, ‘ASDC01’, 2000), (1001, None, None), (1010, None, None), (1008, ‘ASDC01’, 2000), (1002, None, None)]
With this
conn.execute(insert_query, row_chunks)
0
If you are not using the ORM layer, you can do a bulk insert like this:
import sqlalchemy as sa
engine = sa.create_engine(...) # Your engine URL here.
# Reflect the table, or get a reference from a model's `__table__` attribute etc.
tbl = sa.Table('name-of-table', sa.MetaData(), autoload_with=engine)
# Values should be single dict or a list of dicts.
# Bare tuples were acceptable in versions before 2.0.
values = [{'a': 1, 'b': 2}, {'a': 3, 'b': 4}, ...]
with engine.begin() as conn:
conn.execute(tbl.insert(), values)