Simply trying to build a sql query to execute from python. Getting SQL syntax error.
for elem in phraseList:
cursor.execute("SELECT PHRASE,COUNT(ID) FROM TEST.NERD WHERE LABEL LIKE '%PRT%' \
AND ID IN (SELECT DISTINCT ID FROM TEST.NERD WHERE LABEL LIKE '%COND%' \
AND PHRASE LIKE (%s)),(elem)")
However note that when I execute the following (it works perfectly fine):
for elem in phraseList:
cursor.execute("SELECT PHRASE,COUNT(ID) FROM TEST.NERD WHERE LABEL LIKE '%PRT%' \
AND ID IN (SELECT DISTINCT ID FROM TEST.NERD WHERE LABEL LIKE '%COND%' \
AND PHRASE LIKE '%dmg'")
asked May 8, 2013 at 7:38
Yavar
11.9k5 gold badges34 silver badges63 bronze badges
1 Answer 1
You need to make elem a separate parameter, not part of the query string:
cursor.execute("SELECT PHRASE,COUNT(ID) FROM TEST.NERD WHERE LABEL LIKE '%PRT%' \
AND ID IN (SELECT DISTINCT ID FROM TEST.NERD WHERE LABEL LIKE '%COND%' \
AND PHRASE LIKE %s", (elem,))
That last parameter needs to be a tuple with one element, and to create one of those you need to have that one comma there too.
answered May 8, 2013 at 7:40
Martijn Pieters
1.1m326 gold badges4.2k silver badges3.4k bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
Yavar
I have posted another problem that I am facing here now stackoverflow.com/questions/16435676/python-sql-valueerror . Thanks for your help once again.
Martijn Pieters
I'm sorry that I didn't catch on to the
%PART%, etc. problem there; should have realized this could be the MySQLdb adapter. Answered there.default