25

I'd like to bulk insert a list of strings into a MySQL Database with SQLAlchemy Core.

engine = create_engine("mysql+mysqlconnector://...")
meta = MetaData()
meta.bind = engine

My table layout looks like this - together with two currently unused columns (irrelevant1/2):

MyTabe = Table('MyTable', meta,
Column('id', Integer, primary_key=True), 
Column('color', Text),
Column('irrelevant1', Text)
Column('irrelevant2', Text))

Unfortunately the following does not work - it inserts an empty row. What's the right way to do this?

MyTable.insert().execute(['blue', 'red', 'green'])
2
  • 3
    Take a look at the docs for Executing Multiple Statements Commented Sep 9, 2013 at 22:29
  • For very fast insertions, look into using the lower level session.bulk_insert_mappings(Table, lst) See the docs here. Commented Jul 29, 2019 at 17:54

2 Answers 2

42

Here's one way to do it:

MyTable.__table__.insert().execute([{'color': 'blue'}, 
                                    {'color': 'red'}, 
                                    {'color': 'green'}])

Or, using connection.execute():

conn.execute(MyTable.insert(), [{'color': 'blue'}, 
                                {'color': 'red'}, 
                                {'color': 'green'}])

You can easily make a list of dicts from the list you have:

[{'color': value} for value in colors]
Sign up to request clarification or add additional context in comments.

8 Comments

Thanks, would it be possible to just use the list (no dictionaries)?
@fanti well, docs says that yes, this should be a list of dictionaries.
@fanti why don't just make a list of dicts from the list, like I've noted in the answer?
@alecxe: Is there a way to pass hints to the bulk insert statements in SQLAlchemy? so that I can make it even faster? For Eg.: /*+append*/ in Oracle helps bulk inserts speed up much faster.
maybe this helps someone later, we need to use table to access the Table object that is underlying in the class. i.e. MyTable.__table__ = table is equivalent to the Table('MyTable'), meta,....) construct of the classical sqlalchemy method. And insert is a method of the classical Table
|
9

Another way to do it:

from sqlalchemy import MetaData, Table, create_engine

engine = create_engine("mysql+mysqlconnector://....")
metadata = MetaData()
metadata.reflect(engine, only=['MyTable'])
table = Table('MyTable', meta, autoload=True, autoload_with=engine)

engine.execute(table.insert(), [{'color': 'blue'}, 
                            {'color': 'red'}, 
                            {'color': 'green'}])

1 Comment

It's metadata and not meta in the Table initialization no?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.