SQLAlchemy 如何转义 text() 内部的绑定参数?
如何转义传递给 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如文档中所述:
但请记住,反斜杠也是 Python 字符串文字中的转义字符,因此
是不正确的,因为 Python 将要解释
\:
作为转义字符。我们需要使用“原始字符串”(r""
)或转义反斜杠本身
As mentioned in the docs:
But remember that the backslash is also the escape character in Python string literals, so
is incorrect because Python will want to interpret
\:
as an escape character. We need to use either a "raw string" (r""
)or escape the backslash itself