我在 Python 中使用 psycopg2 将一些值传递到 postgres 字符字段中。一些字符串值包含句点、斜杠、引号等。
使用 MySQL,我只需使用
MySQLdb.escape_string(my_string)
是否有 psycopg2 的等价物?
我在 Python 中使用 psycopg2 将一些值传递到 postgres 字符字段中。一些字符串值包含句点、斜杠、引号等。
使用 MySQL,我只需使用
MySQLdb.escape_string(my_string)
是否有 psycopg2 的等价物?
转义是自动的,您只需调用:
cursor.execute("query with params %s %s", ("param1", "pa'ram2"))
(请注意,未使用 python % 运算符)并且值将被正确转义。
您可以使用 手动转义变量extensions.adapt(var)
,但这很容易出错并且不考虑连接编码:它不应该在常规客户端代码中使用。
就像皮罗所说,逃避是自动的。但是有一种方法也可以使用cursor.mogrify(sql, [params])返回由 psycopg2 转义的完整 sql
万一查询参数不够用并且您需要自己转义字符串,您可以将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], )
Psycopg2 没有这样的方法。它具有将 Python 值调整为 ISQLQuote 对象的扩展getquoted()
,并且这些对象具有返回 PostgreSQL 兼容值的方法。
有关如何使用它的示例,请参阅此博客:
2019-03-03 更新:更改了指向 archive.org 的链接,因为九年后,原版不再可用。
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__)