Sqlalchemy核心,从元组而不是dict插入多行

时间:2012-12-27 12:33:23

标签: python sqlite sqlalchemy

我在2D元组中有数据(或者说来自Numpy表),需要将其插入到SQL表中。使用Sqlalchemy Core和SQLite,如何有效地将这些数据插入到我的表中?

从@eclaird获取ie;

engine = sa.create_engine('sqlite://', echo=True)
metadata = sa.MetaData()

widgets_table = sa.Table('widgets', metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('bar', sa.String(50)),
    sa.Column('biz', sa.Boolean),
    sa.Column('baz', sa.Integer),
    )
metadata.create_all(engine)

# Assuming this is the data where None holds place for primary key
my_data = [
    (None, "Test", True, 3),
    (None, "Test", True, 3),
    ]

到目前为止,我在文档中this point;所以我有;

engine.execute(widgets_table.insert().values((None, "Test", True, 3)))

哪个有效。但我想一次插入许多行,例如

engine.execute(widgets_table.insert().values(((None, "Test", True, 3), (None, "Test", True, 3))))

然后错误;

  

具有当前数据库版本设置的'sqlite'方言不支持就地多行插入。

也试过;

insert = widgets_table.insert()

engine.execute(insert, [
                    (None, "Test", True, 3), 
                    (None, "Test", True, 3) 
                    ])

有错误;

  

AttributeError:'tuple'对象没有属性'keys'

最近转换为SQLalch,我在这里有点迷失。

1 个答案:

答案 0 :(得分:3)

你遗漏了一些关于你的设置的细节,所以我做了些什么。除非您也插入表的主键,否则插入元组很困难,那么为什么不在插入之前从数据中创建字典呢?

这应该适用于SQLAlchemy 0.7.6及更高版本:

import sqlalchemy as sa

engine = sa.create_engine('sqlite://', echo=True)
metadata = sa.MetaData()

widgets_table = sa.Table('widgets', metadata,
    sa.Column('id', sa.Integer, primary_key=True),
    sa.Column('foo', sa.String(50)),
    sa.Column('bar', sa.String(50)),
    sa.Column('biz', sa.Boolean),
    sa.Column('baz', sa.Integer),
    )
metadata.create_all(engine)

# Assuming this is your data
values = [
    (None, "Test", True, 3),
    (None, "Test", True, 3),
    ]

with engine.connect() as connection:
    with connection.begin() as transaction:
        try:
            markers = ','.join('?' * len(values[0]))
            ins = 'INSERT INTO {tablename} VALUES ({markers})'
            ins = ins.format(tablename=widgets_table.name, markers=markers)
            connection.execute(ins, values)
        except:
            transaction.rollback()
            raise
        else:
            transaction.commit()