如何将多个数据记录插入表中而忽略重复项。我正在使用SQLAlchemy。
谢谢!
prefix_with("TEXT")
在INSERT
和SQL的其余部分之间添加任意文本。 execute()
接受包含要插入记录的字典列表,或者如果您只想插入单个记录,则接受单个字典。
您正在寻找的行为的SQLite语法:
inserter = table_object.insert().prefix_with("OR REPLACE")
inserter.execute([{'column1':'value1'}, {'column1':'value2'}])
要始终将INSERT
替换为INSERT OR IGNORE
,可以使用compiler extension:
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)
或仅临时执行此操作,请手动调用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)
这确实让人感到棘手,因为它仍然是全局更改,但是只要您不使用线程并确保在deregister
调用之前正确完成所有操作,就可以了。