1

我想完全按照cursor.mogrify生产的方式去做。

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

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

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

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

4

1 回答 1

3

不要使用tuple. 用一个dictionary

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
于 2013-12-20T21:23:51.700 回答