psycopg2 equivalent of mysqldb.escape_string?

后端 未结 5 584
迷失自我
迷失自我 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], )
    

提交回复
热议问题