python - 使用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
有谁知道为什么会这样?解决问题的最佳方法是什么?我可以使用条件来检查元组长度,但我觉得应该有更好的方法......
解决方案
('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']
。
推荐阅读
- c# - 表单提交 - 为每个字段添加额外的参数并在服务器上读取它们
- python-3.x - 如何从已经使用networkx创建的多个节点添加多个边?
- python - Airflow 1.10.2 未将日志写入 S3
- amazon-web-services - 如何在 Redshift(亚马逊)中更新 UDF?
- heroku - 无法在“main”中找到应用程序对象“app”-Heroku CLI
- r - 检查数据框中的特定行组中是否存在值
- r - 缓存矩阵的逆
- ios - 如何将从 ftp URL 检索到的数据转换为 Swift 中的可用对象
- java - 如何让我的回收器适配器检索发送到 firebase 数据库的消息?
- mips - 当我在 MIPS 中使用 sb 命令时,有没有办法确保我的字节正确加载?