关于python:SQLAlchemy INSERT IGNORE | 珊瑚贝

SQLAlchemy INSERT IGNORE


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

谢谢!


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

您要查找的行为的 SQLite 语法:

1
2
inserter = table_object.insert().prefix_with(“OR REPLACE”)
inserter.execute([{‘column1’:‘value1’}, {‘column1’:‘value2’}])

要始终将 INSERT 替换为 INSERT OR IGNORE,您可以使用编译器扩展:

1
2
3
4
5
6
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:

1
2
3
4
5
6
7
8
9
10
11
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 调用之前所有内容都正确提交,它可能没问题。


来源:https://www.codenong.com/2218304/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9416.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?