Skip to content Skip to sidebar Skip to footer

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 = ''' UPDAT

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

Post a Comment for "Python - Format Single Quote In SQL Statement PyODBC"