简体   繁体   English

使用 SQLAlchemy Core 批量插入列表值

[英]bulk insert list values with SQLAlchemy Core

I'd like to bulk insert a list of strings into a MySQL Database with SQLAlchemy Core.我想使用 SQLAlchemy Core 将字符串列表批量插入到 MySQL 数据库中。

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

My table layout looks like this - together with two currently unused columns (irrelevant1/2):我的表格布局如下所示 - 以及两个当前未使用的列(无关 1/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'])

Here's one way to do it:这是一种方法:

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

Or, using connection.execute() :或者,使用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]

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'}])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM