使用 SQLAlchemy Core 批量插入列表值

2021-12-30 00:00:00 python sqlalchemy database mysql

我想使用 SQLAlchemy Core 将字符串列表批量插入到 MySQL 数据库中.

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

我的表格布局如下所示 - 连同两个当前未使用的列(不相关 1/2):

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

推荐答案

这是一种方法:

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

或者,使用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]

相关文章