首页 > 解决方案 > Psycopg2 带有 sql 格式函数的参数化查询

问题描述

我刚刚用 Psycopg2 遇到了这个问题:

cur.execute("select format('%s, %s, %s', 'one', 'two', 'three') from foo where bar = %s", ('baz',))

这会产生元组索引超出范围异常。

很明显,Psycopg 占位符与 sql 格式占位符有冲突。除了在 python 级别格式化字符串之外,还有其他解决方案吗?这将非常有帮助,因为我无法直接控制该 sql。我只是接受它并使用一些预定参数执行它......

标签: pythonpostgresqlpsycopg2

解决方案


使用双百分号:

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'"

推荐阅读