How to insert variables into python when using PostgreSQL

Question:

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
Asked By: mark

||

Answers:

Per the documentation

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.

Answered By: klin

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!

Answered By: xupaii

You are getting the TypeError because you are trying to pass a parameter to the PostgreSQL query using the Python string formatting operator %s, but you are not providing the required value to be formatted.

To fix the error, you need to pass the value of var as an additional argument to execute(), like this:

def some_func(var):
cursor.execute("SELECT * FROM table WHERE attribute = %s", (var,))
return

Note that the value of var must be passed as a tuple, even if it is a single value.

This should correctly substitute the value of var into the query string and avoid the TypeError.

I hope this helps! Let me know if you have any more questions.

Answered By: thuggy codes
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.