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?
The psycopg2-binary package is meant for beginners to start playing with Python and PostgreSQL without the need to meet the build requirements.
Psycopg2 is a DB API 2.0 compliant PostgreSQL driver that is actively developed. It is designed for multi-threaded applications and manages its own connection pool.
Project description. Psycopg is the most popular PostgreSQL database adapter for the Python programming language. Its main features are the complete implementation of the Python DB API 2.0 specification and the thread safety (several threads can share the same connection).
Asynchronous notificationsPsycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY.
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.
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With