gpt4 book ai didi

python - Psycopg2 生产适当的 mogrify?

转载 作者:行者123 更新时间:2023-11-29 12:46:11 25 4
gpt4 key购买 nike

我想做 cursor.mogrify 做的事,但要以适合生产的方式。

我正在更新一些通过连接字符串构建查询的遗留 Python 代码。我需要更改此设置以安全逃生。

查询很长并且构建在与运行不同的服务器上,因此使用 cursor.execute 进行转义的正常过程出于代码清晰度和实际可行性方面的原因都没有吸引力。

我会使用 mogrify,但我知道它仅用于调试目的。

我环顾四周,似乎无法找到一个好的答案。你有什么建议?

最佳答案

不要使用元组。使用字典

d = {'p1': val1, 'p2': val2}
cur.execute("""
select *
from t
where col1 = %(p1)s and col2 = %(p2)s
""", d
)

如果有可选参数则传为null

d = {'p1': None, 'p2': val2}
cur.execute("""
select *
from t
where
(%(p1)s is null or col1 = %(p1)s)
and
(%(p2)s is null or col2 = %(p2)s)
""", d
)

建立到服务器的 ssh 连接并通过它连接。

ssh -L 5432:localhost:5432 remotehost.com

关于python - Psycopg2 生产适当的 mogrify?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20710063/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com