I'm new to python and having some problems escaping characters in a SQL query (MSSQL 2008 R2). There are lines in the file I'm using as input for the query string that have single quotes, parentheses and other characters. They are TV and movie titles:
Tyler Perry's Daddy's Little Girls
Gamer - 3D
American Reunion ('12) (Unrated)
Jarhead 2: Field Of Fire (Unrated)
I'm not quite sure how to do the escape characters properly. Here is my script:
#!/usr/bin/python
import pyodbc
BASE_QUERY = """
SELECT AssetID,AssetName,AssetTypeID,DescriptorXML
FROM AssetLibrary.dbo.ALAsset with(nolock)
WHERE IsDeleted = 0
and (AssetTypeID = 1 or AssetTypeID = 4)
and AssetName like '%%%s%%'
"""
List = []
with open ("C:/Users/josh/Desktop/title-list.txt", "r") as potato:
with pyodbc.connect(DSN='SQL-v13') as con:
cur = con.cursor()
for line in potato:
query = BASE_QUERY % line
cur.execute(query)
results = list(cur.fetchall())
if len(results) > 0:
List.append(results)