psycopg2 相当于 mysqldb.escape_string?

发布于 2024-09-25 09:49:41 字数 203 浏览 6 评论 0原文

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

转义字符串即可。

MySQLdb.escape_string(my_string)

使用 MySQL,我只需使用Is there an equals for psycopg2?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

帅哥哥的热头脑 2024-10-02 09:49:41

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

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

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

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

Escaping is automatic, you just have to call:

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

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

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

七分※倦醒 2024-10-02 09:49:41

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

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

因为看清所以看轻 2024-10-02 09:49:41

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

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

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], )
似最初 2024-10-02 09:49:41

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:参数 2 必须是连接或游标,请尝试:

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

# or

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

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

沩ん囻菔务 2024-10-02 09:49:41

Psycopg2没有这样的方法。它有一个扩展,用于使Python值适应ISQLQuote对象,这些对象有一个 getquoted() 方法来返回 PostgreSQL 兼容的值。

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

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

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

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

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

Quoting bound values in SQL statements using psycopg2

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文