views:

27

answers:

2

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?

+1  A: 

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

Bill Karwin
Notice that the guy there is wrong: what he wants to do can be obtained using the `mogrify()` method (http://initd.org/psycopg/docs/cursor.html#cursor.mogrify)
piro
Thanks @piro, that looks easier, though it is probably intended for using on full SQL expressions or queries, not just individual values to quote.
Bill Karwin
+1  A: 

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.

piro