psycopg2相当于mysqldb.escape_string?

时间:2010-09-29 16:31:00

标签: sql postgresql psycopg2

我在Python中使用psycopg2将一些值传递给postgres字符字段。一些字符串值包含句点,斜杠,引号等。

使用MySQL我只是用

转义字符串
MySQLdb.escape_string(my_string)

是否有psycopg2的等价物?

5 个答案:

答案 0 :(得分:27)

转义是自动的,你只需要打电话:

cursor.execute("query with params %s %s", ("param1", "pa'ram2"))

(注意python%运算符使用)并且值将被正确转义。

您可以使用extensions.adapt(var)手动转义变量,但这很容易出错并且不考虑连接编码:应该在常规客户端代码中使用。

答案 1 :(得分:7)

piro said,一样,逃避是自动的。但是有一种方法可以使用cursor.mogrify(sql, [params])

返回psycopg2转义的完整sql

答案 2 :(得分:1)

如果查询参数不够充分并且您需要自己转义字符串,则可以使用Postgres escaped string constants以及Python repr(因为Python'转义非ascii和unicode字符的规则与Postgres的相同:

def postgres_escape_string(s):
   if not isinstance(s, basestring):
       raise TypeError("%r must be a str or unicode" %(s, ))
   escaped = repr(s)
   if isinstance(s, unicode):
       assert escaped[:1] == 'u'
       escaped = escaped[1:]
   if escaped[:1] == '"':
       escaped = escaped.replace("'", "\\'")
   elif escaped[:1] != "'":
       raise AssertionError("unexpected repr: %s", escaped)
   return "E'%s'" %(escaped[1:-1], )

答案 3 :(得分:0)

Psycopg2没有这样的方法。它有一个extension用于调整Python值到ISQLQuote对象,这些对象有一个getquoted()方法来返回与PostgreSQL兼容的值。

有关如何使用它的示例,请参阅此博客:

Quoting bound values in SQL statements using psycopg2

更新2019-03-03:将链接更改为archive.org,因为九年后,原始版本不再可用。

答案 4 :(得分:0)

psycopg2在2.7版中添加了一个方法,看来: 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)

如果出现类似以下错误: TypeError: argument 2 must be a connection or a cursor,请尝试:

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

# or

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