Python - format single quote in SQL statement PyODBC

て烟熏妆下的殇ゞ 提交于 2019-12-12 06:13:45

问题


I already tried a couple of drivers: pymsql, pyobdc and still have issue with format single quote in SQL. Examples of code below:

CASE 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
                            ))

This code doesn't compile:

"not all arguments converted during string formatting"

CASE 2.

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

I catch the error:

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

once title = u'102.7 The Fan'

CASE 3.

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

Error:

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

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

What is a correct approach to handling it?


回答1:


Your "CASE 1" is essentially correct, but you are not passing the parameters to conn.execute properly. Instead of trying to use string formatting (via the % operator), simply pass the tuple as the second argument to the .execute, like this:

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.")


来源:https://stackoverflow.com/questions/32436268/python-format-single-quote-in-sql-statement-pyodbc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!