python - SQL Alchemy IN 查询中出现 PG8000 异常 : invalid input syntax for type integer: "{2,3,5,6,7}"

标签 python sqlalchemy pg8000

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/

相关文章:

python - 从 Flask 使用 SQLAlchemy session 引发 "SQLite objects created in a thread can only be used in that same thread"

postgresql - pg8000.core.ProgrammingError : 'could not determine data type of parameter $2'

python - 替换列表中的元素

python - Pandas xlrd 引擎传递了静态值错误

python wtf AttributeError : 'ObjectIdField' object has no attribute 'help_text'

python - Pandas Merge 并为重复列创建多索引

heroku - 在外部工作人员中使用 sqlalchemy 声明式

python - 如何通过指定模式从 postgresql 数据库中获取行?

Python/pg8000 WHERE IN 语句

python - postgres 和 pg8000 python 的连接问题 - 清除密码问题?