python - Psycopg2 带有 sql 格式函数的参数化查询
问题描述
我刚刚用 Psycopg2 遇到了这个问题:
cur.execute("select format('%s, %s, %s', 'one', 'two', 'three') from foo where bar = %s", ('baz',))
这会产生元组索引超出范围异常。
很明显,Psycopg 占位符与 sql 格式占位符有冲突。除了在 python 级别格式化字符串之外,还有其他解决方案吗?这将非常有帮助,因为我无法直接控制该 sql。我只是接受它并使用一些预定参数执行它......
解决方案
使用双百分号:
sql = cur.mogrify("select format('%%s, %%s, %%s', 'one', 'two', 'three') from foo where bar = %s", ('baz',))
print(sql)
出去:
"select format('%s, %s, %s', 'one', 'two', 'three') from foo where bar = 'baz'"
推荐阅读
- r - 按类别分组,然后找出类别之间的差异 [r]
- julia - 如何显示二阶数值微分的截断误差是一阶数值微分的平方
- kubernetes - 在 Kubernetes 中使用分片的生产 Redis 集群
- java - 禁止所有带有 PMD 和 XPath 的 java.sql 包
- pandas - 如何解决 pandas 中 set_index 函数的问题
- sql - 使用每一行作为 Insert Into 循环遍历表的行 - SQL
- postgresql - 用于从 PostgreSQL 表中过滤/聚合结果的 GraphQL 查询结构
- java - Docker Image 无法在 jar 中找到主文件
- c - 如何从文件夹中读取C中的文件
- javascript - 如何将 Nativescript 应用程序升级到版本 6?