Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

psycopg2 equivalent of mysqldb.escape_string?

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?

like image 227
AP257 Avatar asked Sep 29 '10 16:09

AP257


People also ask

Does Psycopg2 need PostgreSQL?

The psycopg2-binary package is meant for beginners to start playing with Python and PostgreSQL without the need to meet the build requirements.

Is Psycopg2 a database driver?

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.

What is python3 Psycopg2?

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).

Is Psycopg2 asynchronous?

Asynchronous notificationsPsycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY.


2 Answers

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 image 87
piro Avatar answered Sep 19 '22 16:09

piro


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])

like image 40
notbad.jpeg Avatar answered Sep 21 '22 16:09

notbad.jpeg