0

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

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I have posted another problem that I am facing here now stackoverflow.com/questions/16435676/python-sql-valueerror . Thanks for your help once again.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.