29

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

使用 MySQL,我只需使用

MySQLdb.escape_string(my_string)

是否有 psycopg2 的等价物?

4

5 回答 5

37

转义是自动的,您只需调用:

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

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

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

于 2010-10-06T10:06:21.097 回答
11

就像皮罗所说,逃避是自动的。但是有一种方法也可以使用cursor.mogrify(sql, [params])返回由 psycopg2 转义的完整 sql

于 2013-07-15T13:55:28.987 回答
4

万一查询参数不够用并且您需要自己转义字符串,您可以将Postgres 转义字符串常量与 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], )
于 2015-05-14T22:51:25.230 回答
0

Psycopg2 没有这样的方法。它具有将 Python 值调整为 ISQLQuote 对象的扩展getquoted(),并且这些对象具有返回 PostgreSQL 兼容值的方法。

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

使用 psycopg2 在 SQL 语句中引用绑定值

2019-03-03 更新:更改了指向 archive.org 的链接,因为九年后,原版不再可用。

于 2010-09-29T16:40:25.233 回答
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__)

于 2019-11-19T01:45:30.787 回答