Ore Arowobusoye
Ore Arowobusoye

Reputation: 147

Replacing a String with a python variable in sql query

so I know that similar questions have been asked before, but the solutions posted do not seem to work for me, unless perhaps I am doing it wrong.

I want to change this:query1= ("SELECT anthologyID, title FROM newschema.item WHERE title LIKE 'asperges'" ) where the output is 51962, Asperges

into something like this:

asperges= "asperges" cursor.execute(query1,asperges) query1= ("SELECT anthologyID, title FROM newschema.item WHERE title LIKE '%s'")

problem: output is all wrong (I'm printing in a for loop on the cursor just for reference), and instead of getting just one match, I'm getting a match on all titles in that table.

what's up?

(because someone will probably tell me to do something like this: query1= ("SELECT anthologyID, title FROM newschema.item WHERE title LIKE '%s'" , asperges)

That query is giving me AttributeError: 'tuple' object has no attribute 'encode'

Thanks!

Upvotes: 1

Views: 4209

Answers (1)

mviana
mviana

Reputation: 76

For cursor.execute you can give two arguments: first the string with the values to replace ("%s") and the second one is a tuple, so either you can throw this to your cursor (best option!):

cursor.execute("SELECT anthologyID, title FROM newschema.item WHERE title LIKE %s",('aspergers',))

DO NOT FORGET the comma after 'aspergers'! It converts your data to a tuple.

Or you can set a query and give it to the cursor:

query1= "SELECT anthologyID, title FROM newschema.item WHERE title LIKE %s"  % (asperges,)
cursor.execute(query1)

CHECK THE COMMA again.

Upvotes: 2

Related Questions