SQL psycopg2 相当于 mysqldb.escape_string?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3823735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 07:43:15  来源:igfitidea点击:

psycopg2 equivalent of mysqldb.escape_string?

sqlpostgresqlpsycopg2

提问by AP257

I'm passing some values into a postgres character field using psycopg2 in Python. Some of the string values contain periods, slashes, quotes etc.

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

With MySQL I'd just escape the string with

使用 MySQL 我只是转义字符串

MySQLdb.escape_string(my_string)

Is there an equivalent for psycopg2?

psycopg2 是否有等价物?

回答by piro

Escaping is automatic, you just have to call:

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

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

(notice that the python % operator is notused) and the values will be correctly escaped.

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

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 notsupposed to be used in regular client code.

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

回答by notbad.jpeg

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

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

回答by David Wolever

In the unlikely event that query parameters aren't sufficient and you need to escape strings yourself, you can use Postgres escaped string constantsalong with Python's repr(because Python's rules for escaping non-ascii and unicode characters are the same as Postgres's):

万一查询参数不足并且您需要自己转义字符串,您可以将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], )

回答by getup8

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

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)

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

如果您收到类似的错误: TypeError: argument 2 must be a connection or a cursor,请尝试:

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

# or

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

回答by Bill Karwin

Psycopg2 doesn't have such a method. It has an extensionfor adapting Python values to ISQLQuote objects, and these objects have a getquoted()method to return PostgreSQL-compatible values.

Psycopg2 没有这样的方法。它具有使 Python 值适应 ISQLQuote 对象的扩展,并且这些对象具有getquoted()返回与 PostgreSQL 兼容的值的方法。

See this blog for an example of how to use it:

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

Quoting bound values in SQL statements using psycopg2

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

Update 2019-03-03: changed the link to archive.org, because after nine years, the original is no longer available.

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