如何在SQLAlchemy中使用bindparam读取字符串参数且不带引号?
解决SQLAlchemy绑定数据库标识符时自动加引号的问题
你遇到的问题是因为默认的bindparam会把传入的字符串当作普通值参数处理,所以自动添加引号;但你要绑定的是数据库对象标识符(库/表名),需要用专门的标识符绑定方式,不需要额外字符串格式化,完全符合你的需求。
解决方案1:使用render_as_identifier=True参数(SQLAlchemy 1.4+支持)
直接在bindparam中设置该参数,告诉SQLAlchemy将此参数作为数据库标识符处理,不会添加引号:
import sqlalchemy as sa from sqlalchemy import bindparam query = sa.text("SELECT * FROM :db").bindparams(bindparam('db', '[MyDB].[dbo].[Test]', render_as_identifier=True)) print(query.compile(compile_kwargs={"literal_binds": True})) # 返回 SELECT * FROM [MyDB].[dbo].[Test]
解决方案2:用quoted_name包装标识符(兼容旧版本)
如果你的SQLAlchemy版本较低,可使用quoted_name包装标识符,并指定参数类型为Identifier,同时关闭重复引号避免格式错误:
import sqlalchemy as sa from sqlalchemy import bindparam from sqlalchemy.sql.sqltypes import Identifier # 用quoted_name包装已带括号的标识符,设置quote=False避免重复加引号 db_identifier = sa.sql.expression.quoted_name('[MyDB].[dbo].[Test]', quote=False) query = sa.text("SELECT * FROM :db").bindparams(bindparam('db', db_identifier, type_=Identifier)) print(query.compile(compile_kwargs={"literal_binds": True})) # 返回 SELECT * FROM [MyDB].[dbo].[Test]
为什么quotes=False无效?
quotes参数是针对普通字符串值的引号控制,只影响值参数的引号是否保留,不适用于数据库标识符的绑定逻辑,所以对你的场景不起作用。
内容的提问来源于stack exchange,提问作者jan eisenberg
相关产品推荐
相关产品推荐

