cursor.execute(text("SELECT * FROM pnl WHERE type IN (:types)"))
有效。
以下测试:
cursor.execute(text("SELECT * FROM pnl WHERE type IN (:types)"), types=[2, 3, 5, 6, 7])
cursor.execute(text("SELECT * FROM pnl WHERE type IN (:types)"), types=tuple([2, 3, 5, 6, 7]))
cursor.execute(text("SELECT * FROM pnl WHERE type IN (:types)"), types=list([2, 3, 5, 6, 7]))
抛出异常:
(Background on this error at: https://sqlalche.me/e/14/f405) - Traceback (most recent call last):
File "/Git/argus-periodic/venv/lib/python3.9/site-packages/pg8000/legacy.py", line 252, in execute
self._context = self._c.execute_unnamed(
File "/Git/argus-periodic/venv/lib/python3.9/site-packages/pg8000/core.py", line 649, in execute_unnamed
self.handle_messages(context)
File "/Git/argus-periodic/venv/lib/python3.9/site-packages/pg8000/core.py", line 767, in handle_messages
raise self.error
pg8000.exceptions.DatabaseError: {'S': 'ERROR', 'V': 'ERROR', 'C': '22P02', 'M': 'invalid input syntax for type integer: "{2,3,5,6,7}"', 'F': 'numutils.c', 'L': '323', 'R': 'pg_strtoint32'}
那么我如何传递一个列表以在 sql alchemy 的 IN 查询中使用。
最佳答案
pg8000 和 SQLAlchemy 在处理 IN
子句时都有一些特殊之处,需要在这里考虑。
pg8000 requires参数化 IN
查询采用此形式
SELECT col FROM tbl WHERE col IN (SELECT(unnest(CAST(:params) AS integer[])))
所以代码看起来像这样:
values = {'types': [1, 2, 5]}
q = sa.text('select id from users where id in (select(unnest(cast(:types as integer[]))))')
with engine.connect() as conn:
result = conn.execute(q, values)
# Do stuff with result
另一方面,SQLAlchemy 要求我们将参数标记为 expanding当用作 IN
子句的目标时。
最终的 SQLAlchemy 代码看起来像这样(我认为这更惯用):
values = {'types': [2, 3, 5, 6, 7]}
q = sa.text('select * from pnl where type in :types')
q = q.bindparams(sa.bindparam('types', expanding=True))
with engine.connect() as conn:
result = conn.execute(q, values)
# Do stuff with result.
两条语句的差异是由参数传递方式造成的。 “ native ”pg8000 语句传递一个行对象 ((1, 2, 5),)
,该对象必须是取消嵌套的等。SQLAlchemy 版本接收单独的值:(1, 2, 5 )
。
关于python - SQL Alchemy IN 查询中出现 PG8000 异常 : invalid input syntax for type integer: "{2,3,5,6,7}",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70154350/