python SQLAlchemy 插入忽略

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2218304/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-04 00:05:38  来源:igfitidea点击:

SQLAlchemy INSERT IGNORE

pythoninsertsqlalchemyignore

提问by spacemonkey

How can I insert multiple data records into table ignoring duplicates. I am using SQLAlchemy.

如何将多个数据记录插入表中而忽略重复项。我正在使用 SQLAlchemy。

Thank you!

谢谢!

回答by joeforker

prefix_with("TEXT")adds arbitrary text between INSERTand the rest of the SQL. execute()accepts a list of dictionaries with the records you would like to insert or a single dictionary if you only want to insert a single record.

prefix_with("TEXT")INSERT在 SQL 的其余部分之间添加任意文本。execute()接受包含您要插入的记录的字典列表,或者如果您只想插入单个记录,则接受单个字典。

The SQLite syntax for the behavior you're looking for:

您正在寻找的行为的 SQLite 语法:

inserter = table_object.insert().prefix_with("OR REPLACE")
inserter.execute([{'column1':'value1'}, {'column1':'value2'}])

回答by Thomas

To always replace INSERTby INSERT OR IGNORE, you can use a compiler extension:

要始终替换INSERTINSERT OR IGNORE,您可以使用编译器扩展

from sqlalchemy.ext.compiler import compiles
from sqlalchemy.sql.expression import Insert

@compiles(Insert)
def _prefix_insert_with_ignore(insert, compiler, **kw):
    return compiler.visit_insert(insert.prefix_with('OR IGNORE'), **kw)

Or to do this only temporarily, call the compilesdecorator manually and use deregisteronce you're done:

或者只是暂时执行此操作,请compiles手动调用装饰器并deregister在完成后使用:

from sqlalchemy.ext.compiler import compiles, deregister
from sqlalchemy.sql.expression import Insert

def _prefix_insert_with_ignore(insert, compiler, **kw):
    return compiler.visit_insert(insert.prefix_with('OR IGNORE'), **kw)

compiles(Insert)(_prefix_insert_with_replace)
try:
    # do some inserts...
finally:
    deregister(Insert)

This does feel hacky because it's still a global change, but as long as you don't use threads and make sure everything is properly committed before the deregistercall, it's probably okay.

这确实让人感觉很棘手,因为它仍然是一个全局更改,但是只要您不使用线程并确保在deregister调用之前正确提交所有内容,就可能没问题。