使用SQLAlchemy ORM批量插入 [英] Bulk insert with SQLAlchemy ORM
问题描述
有什么方法可以让SQLAlchemy进行批量插入,而不是插入每个对象.即
Is there any way to get SQLAlchemy to do a bulk insert rather than inserting each individual object. i.e.,
这样做:
INSERT INTO `foo` (`bar`) VALUES (1), (2), (3)
而不是:
INSERT INTO `foo` (`bar`) VALUES (1)
INSERT INTO `foo` (`bar`) VALUES (2)
INSERT INTO `foo` (`bar`) VALUES (3)
我刚刚将一些代码转换为使用sqlalchemy而不是原始sql,尽管现在使用它起来要好得多,但现在似乎要慢一些(最多10倍),我想知道这是否是原因.
I've just converted some code to use sqlalchemy rather than raw sql and although it is now much nicer to work with it seems to be slower now (up to a factor of 10), I'm wondering if this is the reason.
也许我可以更有效地利用会议来改善这种情况.目前,我有autoCommit=False
并在添加了一些内容后执行了session.commit()
.尽管如果在其他地方更改了数据库,这似乎会使数据过时,例如,即使我执行新查询,我仍然可以返回旧结果?
May be I could improve the situation using sessions more efficiently. At the moment I have autoCommit=False
and do a session.commit()
after I've added some stuff. Although this seems to cause the data to go stale if the DB is changed elsewhere, like even if I do a new query I still get old results back?
感谢您的帮助!
推荐答案
SQLAlchemy在版本1.0.0
中引入了该功能:
SQLAlchemy introduced that in version 1.0.0
:
通过这些操作,您现在可以批量插入或更新!
With these operations, you can now do bulk inserts or updates!
例如,您可以执行以下操作:
For instance, you can do:
s = Session()
objects = [
User(name="u1"),
User(name="u2"),
User(name="u3")
]
s.bulk_save_objects(objects)
s.commit()
在这里,将进行批量插入.
Here, a bulk insert will be made.
这篇关于使用SQLAlchemy ORM批量插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!