使用SQLAlchemy Core批量插入列表值 [英] bulk insert list values with SQLAlchemy Core

查看:561
本文介绍了使用SQLAlchemy Core批量插入列表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我的表格布局如下 - 和两个当前未使用的列(无关1/2):

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

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

您可以从列表中轻松地创建一个列表:

  [{'color':value} for colors in colors] 
pre>

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

解决方案

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]

这篇关于使用SQLAlchemy Core批量插入列表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆