Python - 在 SQL 语句 PyODBC 中格式化单引号

Python - format single quote in SQL statement PyODBC

我已经尝试了几个驱动程序:pymsql、pyobdc,但在 SQL 中仍然存在格式单引号问题。以下代码示例:

案例 1.

import pyodbc

UPDATE_SQL3 = """
    UPDATE STATION
    SET
        STATION_NAME = ?,
        STATION_TITLE = ?,
        ACTIVE = ?
    WHERE
        STATION_ID = ?
"""

conn = pyodbc.connect('DRIVER={SQL Server};SERVER=local;DATABASE=DB;UID=me;PWD=pass')
cursor = conn.cursor()

cursor.execute(UPDATE_SQL3 %
                           (name,
                            title,
                            active,
                            id
                            ))

此代码无法编译:

"not all arguments converted during string formatting"

案例 2.

UPDATE_SQL3 = """
    UPDATE STATION
    SET
        STATION_NAME = %s,
        STATION_TITLE = %s,
        ACTIVE = %s
    WHERE
        STATION_ID = %s
"""

我发现错误:

('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'The'. (102) (SQLExecDirectW)")

一次title = u'102.7 The Fan'

案例 3.

UPDATE_SQL3 = """
    UPDATE STATION
    SET
        STATION_NAME = '%s',
        STATION_TITLE = '%s',
        ACTIVE = %s
    WHERE
        STATION_ID = %s
"""

错误:

('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 's'. (102) (SQLExecDirectW)")

其中 name = u'Power Michiana\'s Hits and Hip Hop'

正确的处理方法是什么?

您的 "CASE 1" 本质上是正确的,但您没有正确地将参数传递给 conn.execute。不要尝试使用字符串格式(通过 % 运算符),只需将元组作为第二个参数传递给 .execute,如下所示:

import pyodbc

# test data
name = u"Power Michiana's Hits and Hip Hop"
title = u"(some title)"
active = False
id = 1

conn_str = "DSN=myDb_SQLEXPRESS"
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
UPDATE_SQL3 = """\
UPDATE STATION
SET
    STATION_NAME = ?,
    STATION_TITLE = ?,
    ACTIVE = ?
WHERE
    STATION_ID = ?
"""
cursor.execute(UPDATE_SQL3, (name, title, active, id))
conn.commit()
conn.close()
print("Done.")