Bulk insert with SQLAlchemy ORM(使用 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:
批量操作 - SQLAlchemy 文档
通过这些操作,您现在可以进行批量插入或更新!
With these operations, you can now do bulk inserts or updates!
例如,您可以:
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 批量插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 SQLAlchemy ORM 批量插入
基础教程推荐
- 如何在 SQL 中将 Float 转换为 Varchar 2021-01-01
- 二进制文件到 SQL 数据库 Apache Camel 2021-01-01
- 如何根据该 XML 中的值更新 SQL 中的 XML 2021-01-01
- 在多列上分布任意行 2021-01-01
- 表 './mysql/proc' 被标记为崩溃,应该修复 2022-01-01
- 什么是 orradiag_<user>文件夹? 2022-01-01
- MySQL 中的类型:BigInt(20) 与 Int(20) 2021-01-01
- 在 MySQL 中:如何将表名作为存储过程和/或函数参数传递? 2021-01-01
- mysql选择动态行值作为列名,另一列作为值 2021-01-01
- oracle区分大小写的原因? 2021-01-01
