bblohowiak
bblohowiak

Reputation: 103

How Can I Use A Python Variable In A SQL Query So That Parameters Are Processed?

This should be pretty basic; I am not sure what the error I am making is. I am attempting to query a database using a Python variable in the query and I am able to query successfully with this:

locationIDSelectQuery = ('SELECT locationId FROM stateTemplate WHERE id = 1') cursor.execute(locationIDSelectQuery)

and unsuccessfully with this:

stateTableRowId = 1 cursor.execute("SELECT locationId FROM stateTemplate WHERE id=?", stateTableRowId)

When I try this in the latter it doesn't work either (statetableRowID).

Same error message in both instances: Traceback (most recent call last): line 29, in cursor.execute("SELECT locationId FROM stateTemplate WHERE id=?", (stateTableRowId))

ValueError: Could not process parameters

How can I use a Python variable in my SQL query?

Upvotes: 0

Views: 29

Answers (2)

bblohowiak
bblohowiak

Reputation: 103

I combined the recommendations of @zealous and @juanpa.arrivillaga to arrive at a working solution:stateTableRowId = 1 cursor.execute("SELECT locationId FROM stateTemplate WHERE id=%s", (stateTableRowId,))

My understanding is that it may be preferable for security reasons to use ? instead of %s. I have yet to get that to work with the database to which I'm connecting.

Upvotes: 0

zealous
zealous

Reputation: 7503

try the following, replace ? with %s

stateTableRowId = 1
cursor.execute("SELECT locationId FROM stateTemplate WHERE id=%s", stateTableRowId)

Upvotes: 1

Related Questions