psycopg2 equivalent of mysqldb.escape_string?

后端 未结 5 583
迷失自我
迷失自我 2020-12-10 23:53

I\'m passing some values into a postgres character field using psycopg2 in Python. Some of the string values contain periods, slashes, quotes etc.

With MySQL I\'d ju

相关标签:
5条回答
  • 2020-12-11 00:33

    In the unlikely event that query parameters aren't sufficient and you need to escape strings yourself, you can use Postgres escaped string constants along with Python's repr (because Python's rules for escaping non-ascii and unicode characters are the same as Postgres's):

    def postgres_escape_string(s):
       if not isinstance(s, basestring):
           raise TypeError("%r must be a str or unicode" %(s, ))
       escaped = repr(s)
       if isinstance(s, unicode):
           assert escaped[:1] == 'u'
           escaped = escaped[1:]
       if escaped[:1] == '"':
           escaped = escaped.replace("'", "\\'")
       elif escaped[:1] != "'":
           raise AssertionError("unexpected repr: %s", escaped)
       return "E'%s'" %(escaped[1:-1], )
    
    0 讨论(0)
  • 2020-12-11 00:36

    Like piro said, escaping is automatic. But there's a method to also return the full sql escaped by psycopg2 using cursor.mogrify(sql, [params])

    0 讨论(0)
  • 2020-12-11 00:40

    Psycopg2 doesn't have such a method. It has an extension for adapting Python values to ISQLQuote objects, and these objects have a getquoted() method to return PostgreSQL-compatible values.

    See this blog for an example of how to use it:

    Quoting bound values in SQL statements using psycopg2

    Update 2019-03-03: changed the link to archive.org, because after nine years, the original is no longer available.

    0 讨论(0)
  • 2020-12-11 00:43

    Escaping is automatic, you just have to call:

    cursor.execute("query with params %s %s", ("param1", "pa'ram2"))
    

    (notice that the python % operator is not used) and the values will be correctly escaped.

    You can escape manually a variable using extensions.adapt(var), but this would be error prone and not keep into account the connection encoding: it is not supposed to be used in regular client code.

    0 讨论(0)
  • 2020-12-11 00:44

    psycopg2 added a method in version 2.7 it seems: http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.quote_ident

    from psycopg2.extensions import quote_ident
    
    with psycopg2.connect(<db config>) as conn:
        with conn.cursor() as curs:
            ident = quote_ident('foo', curs)
    

    If you get an error like: TypeError: argument 2 must be a connection or a cursor, try either:

    ident = quote_ident('foo', curs.cursor)
    
    # or
    
    ident = quote_ident('food', curs.__wrapper__)
    
    
    0 讨论(0)
提交回复
热议问题