You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用session.execute执行SQL时报AttributeError: 'str'对象无as_string属性

问题解决:AttributeError: 'str' object has no attribute 'as_string'

原始代码

# 'session' 指向数据库    

t = tuple(a_list_of_ids)
query = "select val from sval where id IN {}".format(t)

ids_to_delete = session.execute(sql_to_string(session, query))

报错信息

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/some_path/find_and_delete_ICE_contracts_non_tradeable_first_alive.py", line 34, in find_ice_contracts_on_dte
    is_tradeable_values_of_ids_to_soft_delete = session.execute(sql_to_string(session, query))
  File "some_path/util/sql_translation.py", line 621, in sql_to_string
    return stmt.as_string(psycopg2_connection)
AttributeError: 'str' object has no attribute 'as_string'

问题原因

sql_to_string函数是用来处理SQLAlchemy的ORM查询对象(比如Select实例)的,但你传入的是手动拼接的字符串SQL,函数误将字符串当作ORM对象调用as_string方法,直接触发报错。另外直接调用session.execute(query)失败,是因为手动拼接SQL容易出现语法问题(比如空列表生成IN ()非法语法、字符串类型ID的单引号转义错误),同时存在SQL注入风险。

修复方案

方案1:参数化文本查询(适配session.execute)

用SQLAlchemy的text函数构建查询,通过参数绑定传递ID列表,彻底避免手动拼接SQL的问题:

from sqlalchemy import text

# 用占位符:ids指代ID列表
query = text("select val from sval where id IN :ids")
# 执行查询时传入参数字典,SQLAlchemy会自动处理格式和转义
result = session.execute(query, {"ids": a_list_of_ids})
# 提取查询结果
ids_to_delete = [row.val for row in result]

方案2:ORM查询(更安全规范)

如果sval表有对应的ORM模型类(比如命名为SVal),直接用ORM语法查询:

from your_model_module import SVal

# 使用in_方法筛选ID列表
query = session.query(SVal.val).filter(SVal.id.in_(a_list_of_ids))
# 获取所有结果
result = query.all()
# 提取val字段值
ids_to_delete = [row[0] for row in result]

内容的提问来源于stack exchange,提问作者jikf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 22:57:11