python 3 单引号转义参数标记

python 3 single quotation escapes parameter marker

嗨,我想重现 sql 命令

SP_HELPTEXT SP_CIW_STEP1

在 cursor.execute 在 pyodb 中,使用 ?作为参数标记 .

import pyodbc

ch = pyodbc.connect('DRIVER={SQL Server};SERVER=xxx;DATABASE=yyy;Trusted_Connection=True')
cur = ch.cursor()


cur.execute("sp_helptext '?'", 'SP_CIW_STEP1')

产生错误:

ProgrammingError: ('The SQL contains 0 parameter markers, but 1 parameters were supplied', 'HY000')


并且(感谢@ryugie)

cur.execute("sp_helptext ?", "'SP_CIW_STEP1'")

也会导致错误:

[SQL Server]The object ''SP_CIW_STEP1'' does not exist in database 'xxx' or is invalid for this operation


同时

cur.execute("? 'SP_CIW_STEP1'", 'sp_helptext')

有效,产生

Out[28]: <pyodbc.Cursor at 0x9c21db0>

看来单引号破坏了参数标记。我试着把 \ 并在字符串前面添加 r 。不起作用。任何帮助在这里表示赞赏。谢谢-

不应引用参数标记,也不应引用参数值。

cur.execute("sp_helptext ?", "SP_CIW_STEP1")

应该可以正常工作。