psycopg2 equivalent of mysqldb.escape_string?

AP257 picture AP257 · Sep 29, 2010 · Viewed 22.2k times · Source

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 just escape the string with

MySQLdb.escape_string(my_string)

Is there an equivalent for psycopg2?

Answer

piro picture piro · Oct 6, 2010

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.