python SQLAlchemy - INSERT OR REPLACE 等效项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/708762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SQLAlchemy - INSERT OR REPLACE equivalent
提问by honzas
does anybody know what is the equivalent to SQL "INSERT OR REPLACE" clause in SQLAlchemy and its SQL expression language?
有谁知道 SQLAlchemy 及其 SQL 表达式语言中的 SQL "INSERT OR REPLACE" 子句的等价物是什么?
Many thanks -- honzas
非常感谢——honzas
采纳答案by DNS
I don't think (correct me if I'm wrong) INSERT OR REPLACE is in any of the SQL standards; it's an SQLite-specific thing. There is MERGE, but that isn't supported by all dialects either. So it's not available in SQLAlchemy's general dialect.
我不认为(如果我错了,请纠正我)INSERT OR REPLACE 不属于任何 SQL 标准;这是 SQLite 特定的东西。有 MERGE,但也不是所有方言都支持。所以它在 SQLAlchemy 的通用方言中不可用。
The cleanest solution is to use Session, as suggested by M. Utku. You could also use SAVEPOINTs to save, try: an insert, except IntegrityError: then rollback and do an update instead. A third solution is to write your INSERT with an OUTER JOIN and a WHERE clause that filters on the rows with nulls.
最干净的解决方案是使用 Session,正如 M. Utku 所建议的那样。您也可以使用 SAVEPOINT 来保存,尝试:插入,除了 IntegrityError:然后回滚并进行更新。第三种解决方案是使用 OUTER JOIN 和 WHERE 子句编写 INSERT,该子句过滤具有空值的行。
回答by Hadrien
What about Session.merge
?
怎么样Session.merge
?
Session.merge(instance, load=True, **kw)
Copy the state an instance onto the persistent instance with the same identifier.
将实例的状态复制到具有相同标识符的持久实例上。
If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session. This operation cascades to associated instances if the association is mapped with cascade="merge".
如果当前没有与会话关联的持久实例,它将被加载。返回持久化实例。如果给定的实例未保存,则保存一个副本并将其作为新的持久化实例返回。给定的实例不会与会话关联。如果关联映射为cascade="merge",则此操作级联到关联的实例。
from http://www.sqlalchemy.org/docs/reference/orm/sessions.html
来自http://www.sqlalchemy.org/docs/reference/orm/sessions.html
回答by M. Utku ALTINKAYA
Session.save_or_update(model)