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

Mat*_*sen 8 python sqlalchemy

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

conn.execute(text("select 'My favorite emoticon is :p' from dual")).fetchone()
Run Code Online (Sandbox Code Playgroud)

将导致:

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)
Run Code Online (Sandbox Code Playgroud)

'

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

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

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

Gor*_*son 5

正如文档中提到的:

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

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

text("select 'My favorite emoticon is \:p' from dual")
Run Code Online (Sandbox Code Playgroud)

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

text(r"select 'My favorite emoticon is \:p' from dual")
Run Code Online (Sandbox Code Playgroud)

或者转义反斜杠本身

text("select 'My favorite emoticon is \\:p' from dual")
Run Code Online (Sandbox Code Playgroud)