SQLAlchemy 如何转义 text() 内部的绑定参数?

发布于 2025-01-09 08:13:55 字数 750 浏览 0 评论 0原文

如何转义传递给 text() 的字符串内部的 : 以防止 SQLAlchemy 将其视为绑定参数?

conn.execute(text("select 'My favorite emoticon is :p' from dual")).fetchone()

将导致:

sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'p'
(Background on this error at: http://sqlalche.me/e/14/cd3x)

'

这有点令人困惑,因为从数据库中选择字符串的上下文中 select 'foo :bar baz' 绑定参数在这里没有多大意义。

看起来我可以使用 \ 来逃避这个问题,但它说它已被弃用:

>>> conn.execute(text("select 'My favorite emoticon is \:p' from dual")).fetchone()
<stdin>:1: DeprecationWarning: invalid escape sequence \:
('My favorite emoticon is :p',)

How can I escape a : inside of a string passed to text() to prevent SQLAlchemy from treating it like a bindparameter?

conn.execute(text("select 'My favorite emoticon is :p' from dual")).fetchone()

Will result in:

sqlalchemy.exc.StatementError: (sqlalchemy.exc.InvalidRequestError) A value is required for bind parameter 'p'
(Background on this error at: http://sqlalche.me/e/14/cd3x)

'

It's a bit confusing because from the context of selecting a string from the database select 'foo :bar baz' a bindparameter doesn't make much sense here.

It looks like I can use a \ to escape this, but it says it is deprecated:

>>> conn.execute(text("select 'My favorite emoticon is \:p' from dual")).fetchone()
<stdin>:1: DeprecationWarning: invalid escape sequence \:
('My favorite emoticon is :p',)

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

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

发布评论

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

评论(1

忘羡 2025-01-16 08:13:55

正如文档中所述:

对于需要逐字冒号的 SQL 语句(如在内联字符串中),请使用反斜杠进行转义

但请记住,反斜杠也是 Python 字符串文字中的转义字符,因此

text("select 'My favorite emoticon is \:p' from dual")

是不正确的,因为 Python 将要解释 \: 作为转义字符。我们需要使用“原始字符串”(r""

text(r"select 'My favorite emoticon is \:p' from dual")

或转义反斜杠本身

text("select 'My favorite emoticon is \\:p' from dual")

As mentioned in the docs:

For SQL statements where a colon is required verbatim, as within an inline string, use a backslash to escape

But remember that the backslash is also the escape character in Python string literals, so

text("select 'My favorite emoticon is \:p' from dual")

is incorrect because Python will want to interpret \: as an escape character. We need to use either a "raw string" (r"")

text(r"select 'My favorite emoticon is \:p' from dual")

or escape the backslash itself

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