SpanishBoy
SpanishBoy

Reputation: 2215

Python - format single quote in SQL statement PyODBC

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?

Upvotes: 2

Views: 6928

Answers (1)

Gord Thompson
Gord Thompson

Reputation: 123549

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

Upvotes: 5

Related Questions