gpt4 book ai didi

python - 如何在 SQLAlchemy 和 Firebird 的自定义查询中将 Python 列表绑定(bind)为参数?

转载 作者:太空宇宙 更新时间:2023-11-03 13:55:46 25 4
gpt4 key购买 nike

环境

我将 Firebird 数据库与 SQLAlchemy 一起用作 ORM 包装器。

背景

我知道通过使用 in_ 可以在 IN 子句中传递 sales_id 列表并获得结果。

我有一个必须使用文本 sql 的用例。

问题

这是我的片段,

conn.execute('select * from sellers where salesid in (:sales_id)', sales_id=[1, 2, 3] ).fetchall()

这总是会抛出token unknown error

我只需要将 sales_id ([1, 2, 3]) 列表传递给绑定(bind)参数 (:sales_id)并得到结果集。

最佳答案

如果使用的 DB-API 驱动程序不提供元组和列表的特殊处理以生成行构造函数和 IN 谓词的表达式,则可以使用 bindparam 提供的有点新的功能“扩展” :

stmt = text('select * from sellers where salesid in :sales_id') 
stmt = stmt.bindparams(bindparam('sales_id', expanding=True))

conn.execute(stmt, sales_id=[1, 2, 3]).fetchall()

这将根据每个查询将占位符 sales_id 替换为所需的占位符,以适应用作参数的序列。

关于python - 如何在 SQLAlchemy 和 Firebird 的自定义查询中将 Python 列表绑定(bind)为参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55811285/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com