build SQL dynamic query with psycopg2 python library and using good conversion type tools

后端 未结 3 1388
野的像风
野的像风 2020-12-21 18:52

I have some problem to design a good algorithm which use specification of psycopg2 library described here

I want to build a dynamic query equal to this string :

3条回答
  •  不知归路
    2020-12-21 19:42

    The proper way is to use psycopg2 2.7's new sql module which includes an Identifier object. This allows you to dynamically specify SQL identifiers in a safe way.

    Unfortunately 2.7 is not on PyPi yet (2.6.2 as of writing).

    Until then, psycopg2 cover this under the heading "How can I pass field/table names to a query?" http://initd.org/psycopg/docs/faq.html#problems-with-type-conversions

    You can pass SQL identifiers in along with data values to the execute function by using the AsIs function.

    Note: this provides NO security. It is as good as using a format string, which is not recommended. The only real advantage of this is you encourage future code to follow the execute + data style. You can also easily search for AsIs in future.

    from psycopg2.extensions import AsIs
    
    with transaction() as cur:
        # WARNING: not secure
        cur.execute('SELECT * from %(table)s', {'table': AsIs('mytable')})
    

提交回复
热议问题