首页 > 解决方案 > 使用python f-string构建sql查询IN子句

问题描述

我正在尝试在 python 中使用 f-string 来构建我的 sql 查询。

下面的查询似乎很好:

code = ('123', '234')
print( f"select * from tbl where code in {code} ")

"select * from tbl where code in ('123', '234') "

但是,如果元组中只有一个元素,则不起作用:

code = ('123')
print( f"select * from tbl where code in {code} ")

select * from tbl where code in 123

有谁知道为什么会这样?解决问题的最佳方法是什么?我可以使用条件来检查元组长度,但我觉得应该有更好的方法......

标签: pythonsqlstring-formatting

解决方案


('123')不是元组,Python 解释为简单的字符串'123'。为了获得具有单个元素的元组,您需要在元素后添加一个逗号:('123',)。然后代码

code = ('123',)
print( f"select * from tbl where code in {code} ")

给出:

select * from tbl where code in ('123',)

但是,这仍然不好,因为现在逗号出现在查询中。这可以通过更多格式来解决:

code = ('123',)
scode = ", ".join(f"'{s}'" for s in code)
print( f"select * from tbl where code in ({scode}) ")

这给出了:

select * from tbl where code in ('123') 

这适用于任何大小的元组。例如,

code = ('123', '456')
scode = ", ".join(f"'{s}'" for s in code)
print( f"select * from tbl where code in ({scode}) ")

给出:

select * from tbl where code in ('123', '456') 

如果带有单个元素的元组中的附加逗号似乎很容易错过,您可以使用上面的代码,但使用列表而不是元组。所以:code = ['123']code = ['123', '456']


推荐阅读