Reputation: 165
So I'm sure there is already a solution out there for my question but I haven't been able to see an answer that helps me understand it clearly.
I want to use a function that takes in a variable and uses that variable in a PostgreSQL select statement.
This is my attempt which is incorrect.
def some_func(var):
cursor.execute("SELECT * FROM table WHERE attribute = %s",var)
return
So if I am to run some_func("height"), I want the postgres statement to be executed as follows:
SELECT * FROM table WHERE attribute = 'height';
I got the error:
TypeError: not all arguments converted during string formatting
Upvotes: 4
Views: 1683
Reputation: 121624
Parameters may be provided as sequence or mapping and will be bound to variables in the operation.
Place the variable in a sequence:
cursor.execute("SELECT * FROM table WHERE attribute = %s", [var])
Read also Passing parameters to SQL queries.
Upvotes: 4
Reputation: 475
When string formatting, don't use a comma, but another percentage. In your case, this would be:
def some_func(var):
cursor.execute("SELECT * FROM table WHERE attribute = %s" % var)
return
This should achieve what you are aiming for, if not please comment!
Upvotes: -1