psycopg2 equivalent of mysqldb.escape_string?

Viewed 27351

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?

5 Answers

psycopg2 added a method in version 2.7 it seems: http://initd.org/psycopg/docs/extensions.html#psycopg2.extensions.quote_ident

from psycopg2.extensions import quote_ident

with psycopg2.connect(<db config>) as conn:
    with conn.cursor() as curs:
        ident = quote_ident('foo', curs)

If you get an error like: TypeError: argument 2 must be a connection or a cursor, try either:

ident = quote_ident('foo', curs.cursor)

# or

ident = quote_ident('food', curs.__wrapper__)

Related