Yavar
Yavar

Reputation: 11933

Python SQL ValueError

I am getting the following error:

query=query%db.literal(args)
ValueError: Unsupported Format character 'P' (0x50)

Here is my query being executed from python (note that phraseList is a list)

for elem in phraseList:
    cursor.execute("""SELECT PHRASE,COUNT(CASEID) FROM TEST.NER WHERE LABEL LIKE '%PART%' \
    AND CASEID IN (SELECT DISTINCT CASEID FROM TEST.NER WHERE LABEL LIKE '%CONDITION%'\
    AND PHRASE LIKEPHRASE LIKE %s""",(elem,))

Upvotes: 2

Views: 413

Answers (2)

Yavar
Yavar

Reputation: 11933

Here is what made the error disappear:

for elem in phraseList:
    part='%part%'
    condition='%condition%'
    query="SELECT PHRASE,COUNT(CASEID) FROM TEST.NER WHERE LABEL LIKE %s \
    AND CASEID IN (SELECT DISTINCT CASEID FROM TEST.NER WHERE LABEL LIKE %s \
    AND PHRASE LIKE %s)"
    params=(part,condition,elem)
    cursor.execute(query,params)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121386

MySQLdb overloads the Python string formatting syntax, and the %P part of %PART% is seen as a string formatting expression.

To prevent this you need to double the character to %%:

for elem in phraseList:
    cursor.execute("""SELECT PHRASE,COUNT(CASEID) FROM TEST.NER WHERE LABEL LIKE '%%PART%%' \
    AND CASEID IN (SELECT DISTINCT CASEID FROM TEST.NER WHERE LABEL LIKE '%%CONDITION%%'\
    AND PHRASE LIKEPHRASE LIKE %s""",(elem,))

Upvotes: 2

Related Questions